babylon.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var r = start.r + ((end.r - start.r) * amount);
  1781. var g = start.g + ((end.g - start.g) * amount);
  1782. var b = start.b + ((end.b - start.b) * amount);
  1783. return new Color3(r, g, b);
  1784. };
  1785. /**
  1786. * Returns a Color3 value containing a red color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Red = function () { return new Color3(1, 0, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a green color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Green = function () { return new Color3(0, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a blue color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a black color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Black = function () { return new Color3(0, 0, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a white color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.White = function () { return new Color3(1, 1, 1); };
  1810. /**
  1811. * Returns a Color3 value containing a purple color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1815. /**
  1816. * Returns a Color3 value containing a magenta color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1820. /**
  1821. * Returns a Color3 value containing a yellow color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1825. /**
  1826. * Returns a Color3 value containing a gray color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1830. /**
  1831. * Returns a Color3 value containing a teal color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1835. /**
  1836. * Returns a Color3 value containing a random color
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1840. return Color3;
  1841. }());
  1842. BABYLON.Color3 = Color3;
  1843. /**
  1844. * Class used to hold a RBGA color
  1845. */
  1846. var Color4 = /** @class */ (function () {
  1847. /**
  1848. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1849. * @param r defines the red component (between 0 and 1, default is 0)
  1850. * @param g defines the green component (between 0 and 1, default is 0)
  1851. * @param b defines the blue component (between 0 and 1, default is 0)
  1852. * @param a defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. function Color4(
  1855. /**
  1856. * Defines the red component (between 0 and 1, default is 0)
  1857. */
  1858. r,
  1859. /**
  1860. * Defines the green component (between 0 and 1, default is 0)
  1861. */
  1862. g,
  1863. /**
  1864. * Defines the blue component (between 0 and 1, default is 0)
  1865. */
  1866. b,
  1867. /**
  1868. * Defines the alpha component (between 0 and 1, default is 1)
  1869. */
  1870. a) {
  1871. if (r === void 0) { r = 0; }
  1872. if (g === void 0) { g = 0; }
  1873. if (b === void 0) { b = 0; }
  1874. if (a === void 0) { a = 1; }
  1875. this.r = r;
  1876. this.g = g;
  1877. this.b = b;
  1878. this.a = a;
  1879. }
  1880. // Operators
  1881. /**
  1882. * Adds in place the given Color4 values to the current Color4 object
  1883. * @param right defines the second operand
  1884. * @returns the current updated Color4 object
  1885. */
  1886. Color4.prototype.addInPlace = function (right) {
  1887. this.r += right.r;
  1888. this.g += right.g;
  1889. this.b += right.b;
  1890. this.a += right.a;
  1891. return this;
  1892. };
  1893. /**
  1894. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1895. * @returns the new array
  1896. */
  1897. Color4.prototype.asArray = function () {
  1898. var result = new Array();
  1899. this.toArray(result, 0);
  1900. return result;
  1901. };
  1902. /**
  1903. * Stores from the starting index in the given array the Color4 successive values
  1904. * @param array defines the array where to store the r,g,b components
  1905. * @param index defines an optional index in the target array to define where to start storing values
  1906. * @returns the current Color4 object
  1907. */
  1908. Color4.prototype.toArray = function (array, index) {
  1909. if (index === undefined) {
  1910. index = 0;
  1911. }
  1912. array[index] = this.r;
  1913. array[index + 1] = this.g;
  1914. array[index + 2] = this.b;
  1915. array[index + 3] = this.a;
  1916. return this;
  1917. };
  1918. /**
  1919. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1920. * @param right defines the second operand
  1921. * @returns a new Color4 object
  1922. */
  1923. Color4.prototype.add = function (right) {
  1924. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1925. };
  1926. /**
  1927. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1928. * @param right defines the second operand
  1929. * @returns a new Color4 object
  1930. */
  1931. Color4.prototype.subtract = function (right) {
  1932. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1933. };
  1934. /**
  1935. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1936. * @param right defines the second operand
  1937. * @param result defines the Color4 object where to store the result
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.subtractToRef = function (right, result) {
  1941. result.r = this.r - right.r;
  1942. result.g = this.g - right.g;
  1943. result.b = this.b - right.b;
  1944. result.a = this.a - right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new Color4 with the current Color4 values multiplied by scale
  1949. * @param scale defines the scaling factor to apply
  1950. * @returns a new Color4 object
  1951. */
  1952. Color4.prototype.scale = function (scale) {
  1953. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1954. };
  1955. /**
  1956. * Multiplies the current Color4 values by scale and stores the result in "result"
  1957. * @param scale defines the scaling factor to apply
  1958. * @param result defines the Color4 object where to store the result
  1959. * @returns the current unmodified Color4
  1960. */
  1961. Color4.prototype.scaleToRef = function (scale, result) {
  1962. result.r = this.r * scale;
  1963. result.g = this.g * scale;
  1964. result.b = this.b * scale;
  1965. result.a = this.a * scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Scale the current Color4 values by a factor and add the result to a given Color4
  1970. * @param scale defines the scale factor
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the unmodified current Color4
  1973. */
  1974. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1975. result.r += this.r * scale;
  1976. result.g += this.g * scale;
  1977. result.b += this.b * scale;
  1978. result.a += this.a * scale;
  1979. return this;
  1980. };
  1981. /**
  1982. * Clamps the rgb values by the min and max values and stores the result into "result"
  1983. * @param min defines minimum clamping value (default is 0)
  1984. * @param max defines maximum clamping value (default is 1)
  1985. * @param result defines color to store the result into.
  1986. * @returns the cuurent Color4
  1987. */
  1988. Color4.prototype.clampToRef = function (min, max, result) {
  1989. if (min === void 0) { min = 0; }
  1990. if (max === void 0) { max = 1; }
  1991. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1992. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1993. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1994. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1995. return this;
  1996. };
  1997. /**
  1998. * Multipy an Color4 value by another and return a new Color4 object
  1999. * @param color defines the Color4 value to multiply by
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.multiply = function (color) {
  2003. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2004. };
  2005. /**
  2006. * Multipy a Color4 value by another and push the result in a reference value
  2007. * @param color defines the Color4 value to multiply by
  2008. * @param result defines the Color4 to fill the result in
  2009. * @returns the result Color4
  2010. */
  2011. Color4.prototype.multiplyToRef = function (color, result) {
  2012. result.r = this.r * color.r;
  2013. result.g = this.g * color.g;
  2014. result.b = this.b * color.b;
  2015. result.a = this.a * color.a;
  2016. return result;
  2017. };
  2018. /**
  2019. * Creates a string with the Color4 current values
  2020. * @returns the string representation of the Color4 object
  2021. */
  2022. Color4.prototype.toString = function () {
  2023. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2024. };
  2025. /**
  2026. * Returns the string "Color4"
  2027. * @returns "Color4"
  2028. */
  2029. Color4.prototype.getClassName = function () {
  2030. return "Color4";
  2031. };
  2032. /**
  2033. * Compute the Color4 hash code
  2034. * @returns an unique number that can be used to hash Color4 objects
  2035. */
  2036. Color4.prototype.getHashCode = function () {
  2037. var hash = this.r || 0;
  2038. hash = (hash * 397) ^ (this.g || 0);
  2039. hash = (hash * 397) ^ (this.b || 0);
  2040. hash = (hash * 397) ^ (this.a || 0);
  2041. return hash;
  2042. };
  2043. /**
  2044. * Creates a new Color4 copied from the current one
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.prototype.clone = function () {
  2048. return new Color4(this.r, this.g, this.b, this.a);
  2049. };
  2050. /**
  2051. * Copies the given Color4 values into the current one
  2052. * @param source defines the source Color4 object
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.copyFrom = function (source) {
  2056. this.r = source.r;
  2057. this.g = source.g;
  2058. this.b = source.b;
  2059. this.a = source.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Copies the given float values into the current one
  2064. * @param r defines the red component to read from
  2065. * @param g defines the green component to read from
  2066. * @param b defines the blue component to read from
  2067. * @param a defines the alpha component to read from
  2068. * @returns the current updated Color4 object
  2069. */
  2070. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2071. this.r = r;
  2072. this.g = g;
  2073. this.b = b;
  2074. this.a = a;
  2075. return this;
  2076. };
  2077. /**
  2078. * Copies the given float values into the current one
  2079. * @param r defines the red component to read from
  2080. * @param g defines the green component to read from
  2081. * @param b defines the blue component to read from
  2082. * @param a defines the alpha component to read from
  2083. * @returns the current updated Color4 object
  2084. */
  2085. Color4.prototype.set = function (r, g, b, a) {
  2086. return this.copyFromFloats(r, g, b, a);
  2087. };
  2088. /**
  2089. * Compute the Color4 hexadecimal code as a string
  2090. * @returns a string containing the hexadecimal representation of the Color4 object
  2091. */
  2092. Color4.prototype.toHexString = function () {
  2093. var intR = (this.r * 255) | 0;
  2094. var intG = (this.g * 255) | 0;
  2095. var intB = (this.b * 255) | 0;
  2096. var intA = (this.a * 255) | 0;
  2097. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2098. };
  2099. /**
  2100. * Computes a new Color4 converted from the current one to linear space
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.toLinearSpace = function () {
  2104. var convertedColor = new Color4();
  2105. this.toLinearSpaceToRef(convertedColor);
  2106. return convertedColor;
  2107. };
  2108. /**
  2109. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2110. * @param convertedColor defines the Color4 object where to store the linear space version
  2111. * @returns the unmodified Color4
  2112. */
  2113. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2117. convertedColor.a = this.a;
  2118. return this;
  2119. };
  2120. /**
  2121. * Computes a new Color4 converted from the current one to gamma space
  2122. * @returns a new Color4 object
  2123. */
  2124. Color4.prototype.toGammaSpace = function () {
  2125. var convertedColor = new Color4();
  2126. this.toGammaSpaceToRef(convertedColor);
  2127. return convertedColor;
  2128. };
  2129. /**
  2130. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2131. * @param convertedColor defines the Color4 object where to store the gamma space version
  2132. * @returns the unmodified Color4
  2133. */
  2134. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2135. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2136. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2137. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2138. convertedColor.a = this.a;
  2139. return this;
  2140. };
  2141. // Statics
  2142. /**
  2143. * Creates a new Color4 from the string containing valid hexadecimal values
  2144. * @param hex defines a string containing valid hexadecimal values
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.FromHexString = function (hex) {
  2148. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2149. return new Color4(0.0, 0.0, 0.0, 0.0);
  2150. }
  2151. var r = parseInt(hex.substring(1, 3), 16);
  2152. var g = parseInt(hex.substring(3, 5), 16);
  2153. var b = parseInt(hex.substring(5, 7), 16);
  2154. var a = parseInt(hex.substring(7, 9), 16);
  2155. return Color4.FromInts(r, g, b, a);
  2156. };
  2157. /**
  2158. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.Lerp = function (left, right, amount) {
  2165. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2166. Color4.LerpToRef(left, right, amount, result);
  2167. return result;
  2168. };
  2169. /**
  2170. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2171. * @param left defines the start value
  2172. * @param right defines the end value
  2173. * @param amount defines the gradient factor
  2174. * @param result defines the Color4 object where to store data
  2175. */
  2176. Color4.LerpToRef = function (left, right, amount, result) {
  2177. result.r = left.r + (right.r - left.r) * amount;
  2178. result.g = left.g + (right.g - left.g) * amount;
  2179. result.b = left.b + (right.b - left.b) * amount;
  2180. result.a = left.a + (right.a - left.a) * amount;
  2181. };
  2182. /**
  2183. * Creates a new Color4 from the starting index element of the given array
  2184. * @param array defines the source array to read from
  2185. * @param offset defines the offset in the source array
  2186. * @returns a new Color4 object
  2187. */
  2188. Color4.FromArray = function (array, offset) {
  2189. if (offset === void 0) { offset = 0; }
  2190. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2191. };
  2192. /**
  2193. * Creates a new Color3 from integer values (< 256)
  2194. * @param r defines the red component to read from (value between 0 and 255)
  2195. * @param g defines the green component to read from (value between 0 and 255)
  2196. * @param b defines the blue component to read from (value between 0 and 255)
  2197. * @param a defines the alpha component to read from (value between 0 and 255)
  2198. * @returns a new Color3 object
  2199. */
  2200. Color4.FromInts = function (r, g, b, a) {
  2201. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2202. };
  2203. /**
  2204. * Check the content of a given array and convert it to an array containing RGBA data
  2205. * If the original array was already containing count * 4 values then it is returned directly
  2206. * @param colors defines the array to check
  2207. * @param count defines the number of RGBA data to expect
  2208. * @returns an array containing count * 4 values (RGBA)
  2209. */
  2210. Color4.CheckColors4 = function (colors, count) {
  2211. // Check if color3 was used
  2212. if (colors.length === count * 3) {
  2213. var colors4 = [];
  2214. for (var index = 0; index < colors.length; index += 3) {
  2215. var newIndex = (index / 3) * 4;
  2216. colors4[newIndex] = colors[index];
  2217. colors4[newIndex + 1] = colors[index + 1];
  2218. colors4[newIndex + 2] = colors[index + 2];
  2219. colors4[newIndex + 3] = 1.0;
  2220. }
  2221. return colors4;
  2222. }
  2223. return colors;
  2224. };
  2225. return Color4;
  2226. }());
  2227. BABYLON.Color4 = Color4;
  2228. /**
  2229. * Class representing a vector containing 2 coordinates
  2230. */
  2231. var Vector2 = /** @class */ (function () {
  2232. /**
  2233. * Creates a new Vector2 from the given x and y coordinates
  2234. * @param x defines the first coordinate
  2235. * @param y defines the second coordinate
  2236. */
  2237. function Vector2(
  2238. /** defines the first coordinate */
  2239. x,
  2240. /** defines the second coordinate */
  2241. y) {
  2242. if (x === void 0) { x = 0; }
  2243. if (y === void 0) { y = 0; }
  2244. this.x = x;
  2245. this.y = y;
  2246. }
  2247. /**
  2248. * Gets a string with the Vector2 coordinates
  2249. * @returns a string with the Vector2 coordinates
  2250. */
  2251. Vector2.prototype.toString = function () {
  2252. return "{X: " + this.x + " Y:" + this.y + "}";
  2253. };
  2254. /**
  2255. * Gets class name
  2256. * @returns the string "Vector2"
  2257. */
  2258. Vector2.prototype.getClassName = function () {
  2259. return "Vector2";
  2260. };
  2261. /**
  2262. * Gets current vector hash code
  2263. * @returns the Vector2 hash code as a number
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2273. * @param array defines the source array
  2274. * @param index defines the offset in source array
  2275. * @returns the current Vector2
  2276. */
  2277. Vector2.prototype.toArray = function (array, index) {
  2278. if (index === void 0) { index = 0; }
  2279. array[index] = this.x;
  2280. array[index + 1] = this.y;
  2281. return this;
  2282. };
  2283. /**
  2284. * Copy the current vector to an array
  2285. * @returns a new array with 2 elements: the Vector2 coordinates.
  2286. */
  2287. Vector2.prototype.asArray = function () {
  2288. var result = new Array();
  2289. this.toArray(result, 0);
  2290. return result;
  2291. };
  2292. /**
  2293. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2294. * @param source defines the source Vector2
  2295. * @returns the current updated Vector2
  2296. */
  2297. Vector2.prototype.copyFrom = function (source) {
  2298. this.x = source.x;
  2299. this.y = source.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Sets the Vector2 coordinates with the given floats
  2304. * @param x defines the first coordinate
  2305. * @param y defines the second coordinate
  2306. * @returns the current updated Vector2
  2307. */
  2308. Vector2.prototype.copyFromFloats = function (x, y) {
  2309. this.x = x;
  2310. this.y = y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given floats
  2315. * @param x defines the first coordinate
  2316. * @param y defines the second coordinate
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.set = function (x, y) {
  2320. return this.copyFromFloats(x, y);
  2321. };
  2322. /**
  2323. * Add another vector with the current one
  2324. * @param otherVector defines the other vector
  2325. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2326. */
  2327. Vector2.prototype.add = function (otherVector) {
  2328. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2332. * @param otherVector defines the other vector
  2333. * @param result defines the target vector
  2334. * @returns the unmodified current Vector2
  2335. */
  2336. Vector2.prototype.addToRef = function (otherVector, result) {
  2337. result.x = this.x + otherVector.x;
  2338. result.y = this.y + otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2343. * @param otherVector defines the other vector
  2344. * @returns the current updated Vector2
  2345. */
  2346. Vector2.prototype.addInPlace = function (otherVector) {
  2347. this.x += otherVector.x;
  2348. this.y += otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns a new Vector2
  2355. */
  2356. Vector2.prototype.addVector3 = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2361. * @param otherVector defines the other vector
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.subtract = function (otherVector) {
  2365. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2366. };
  2367. /**
  2368. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2369. * @param otherVector defines the other vector
  2370. * @param result defines the target vector
  2371. * @returns the unmodified current Vector2
  2372. */
  2373. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2374. result.x = this.x - otherVector.x;
  2375. result.y = this.y - otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @returns the current updated Vector2
  2382. */
  2383. Vector2.prototype.subtractInPlace = function (otherVector) {
  2384. this.x -= otherVector.x;
  2385. this.y -= otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Multiplies in place the current Vector2 coordinates by the given ones
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2394. this.x *= otherVector.x;
  2395. this.y *= otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.multiply = function (otherVector) {
  2404. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2405. };
  2406. /**
  2407. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2413. result.x = this.x * otherVector.x;
  2414. result.y = this.y * otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2419. * @param x defines the first coordinate
  2420. * @param y defines the second coordinate
  2421. * @returns a new Vector2
  2422. */
  2423. Vector2.prototype.multiplyByFloats = function (x, y) {
  2424. return new Vector2(this.x * x, this.y * y);
  2425. };
  2426. /**
  2427. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2428. * @param otherVector defines the other vector
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.divide = function (otherVector) {
  2432. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2433. };
  2434. /**
  2435. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @param result defines the target vector
  2438. * @returns the unmodified current Vector2
  2439. */
  2440. Vector2.prototype.divideToRef = function (otherVector, result) {
  2441. result.x = this.x / otherVector.x;
  2442. result.y = this.y / otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Divides the current Vector2 coordinates by the given ones
  2447. * @param otherVector defines the other vector
  2448. * @returns the current updated Vector2
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Gets a new Vector2 with current Vector2 negated coordinates
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.negate = function () {
  2458. return new Vector2(-this.x, -this.y);
  2459. };
  2460. /**
  2461. * Multiply the Vector2 coordinates by scale
  2462. * @param scale defines the scaling factor
  2463. * @returns the current updated Vector2
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2472. * @param scale defines the scaling factor
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.scale = function (scale) {
  2476. var result = new Vector2(0, 0);
  2477. this.scaleToRef(scale, result);
  2478. return result;
  2479. };
  2480. /**
  2481. * Scale the current Vector2 values by a factor to a given Vector2
  2482. * @param scale defines the scale factor
  2483. * @param result defines the Vector2 object where to store the result
  2484. * @returns the unmodified current Vector2
  2485. */
  2486. Vector2.prototype.scaleToRef = function (scale, result) {
  2487. result.x = this.x * scale;
  2488. result.y = this.y * scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2493. * @param scale defines the scale factor
  2494. * @param result defines the Vector2 object where to store the result
  2495. * @returns the unmodified current Vector2
  2496. */
  2497. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2498. result.x += this.x * scale;
  2499. result.y += this.y * scale;
  2500. return this;
  2501. };
  2502. /**
  2503. * Gets a boolean if two vectors are equals
  2504. * @param otherVector defines the other vector
  2505. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Gets a boolean if two vectors are equals (using an epsilon value)
  2512. * @param otherVector defines the other vector
  2513. * @param epsilon defines the minimal distance to consider equality
  2514. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2515. */
  2516. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2517. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2518. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2519. };
  2520. /**
  2521. * Gets a new Vector2 from current Vector2 floored values
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.prototype.floor = function () {
  2525. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2526. };
  2527. /**
  2528. * Gets a new Vector2 from current Vector2 floored values
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.fract = function () {
  2532. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2533. };
  2534. // Properties
  2535. /**
  2536. * Gets the length of the vector
  2537. * @returns the vector length (float)
  2538. */
  2539. Vector2.prototype.length = function () {
  2540. return Math.sqrt(this.x * this.x + this.y * this.y);
  2541. };
  2542. /**
  2543. * Gets the vector squared length
  2544. * @returns the vector squared length (float)
  2545. */
  2546. Vector2.prototype.lengthSquared = function () {
  2547. return (this.x * this.x + this.y * this.y);
  2548. };
  2549. // Methods
  2550. /**
  2551. * Normalize the vector
  2552. * @returns the current updated Vector2
  2553. */
  2554. Vector2.prototype.normalize = function () {
  2555. var len = this.length();
  2556. if (len === 0)
  2557. return this;
  2558. var num = 1.0 / len;
  2559. this.x *= num;
  2560. this.y *= num;
  2561. return this;
  2562. };
  2563. /**
  2564. * Gets a new Vector2 copied from the Vector2
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.prototype.clone = function () {
  2568. return new Vector2(this.x, this.y);
  2569. };
  2570. // Statics
  2571. /**
  2572. * Gets a new Vector2(0, 0)
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.Zero = function () {
  2576. return new Vector2(0, 0);
  2577. };
  2578. /**
  2579. * Gets a new Vector2(1, 1)
  2580. * @returns a new Vector2
  2581. */
  2582. Vector2.One = function () {
  2583. return new Vector2(1, 1);
  2584. };
  2585. /**
  2586. * Gets a new Vector2 set from the given index element of the given array
  2587. * @param array defines the data source
  2588. * @param offset defines the offset in the data source
  2589. * @returns a new Vector2
  2590. */
  2591. Vector2.FromArray = function (array, offset) {
  2592. if (offset === void 0) { offset = 0; }
  2593. return new Vector2(array[offset], array[offset + 1]);
  2594. };
  2595. /**
  2596. * Sets "result" from the given index element of the given array
  2597. * @param array defines the data source
  2598. * @param offset defines the offset in the data source
  2599. * @param result defines the target vector
  2600. */
  2601. Vector2.FromArrayToRef = function (array, offset, result) {
  2602. result.x = array[offset];
  2603. result.y = array[offset + 1];
  2604. };
  2605. /**
  2606. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2607. * @param value1 defines 1st point of control
  2608. * @param value2 defines 2nd point of control
  2609. * @param value3 defines 3rd point of control
  2610. * @param value4 defines 4th point of control
  2611. * @param amount defines the interpolation factor
  2612. * @returns a new Vector2
  2613. */
  2614. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2615. var squared = amount * amount;
  2616. var cubed = amount * squared;
  2617. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2618. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2619. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2620. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2621. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2622. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2623. return new Vector2(x, y);
  2624. };
  2625. /**
  2626. * 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".
  2627. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2628. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2629. * @param value defines the value to clamp
  2630. * @param min defines the lower limit
  2631. * @param max defines the upper limit
  2632. * @returns a new Vector2
  2633. */
  2634. Vector2.Clamp = function (value, min, max) {
  2635. var x = value.x;
  2636. x = (x > max.x) ? max.x : x;
  2637. x = (x < min.x) ? min.x : x;
  2638. var y = value.y;
  2639. y = (y > max.y) ? max.y : y;
  2640. y = (y < min.y) ? min.y : y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2645. * @param value1 defines the 1st control point
  2646. * @param tangent1 defines the outgoing tangent
  2647. * @param value2 defines the 2nd control point
  2648. * @param tangent2 defines the incoming tangent
  2649. * @param amount defines the interpolation factor
  2650. * @returns a new Vector2
  2651. */
  2652. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2653. var squared = amount * amount;
  2654. var cubed = amount * squared;
  2655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2657. var part3 = (cubed - (2.0 * squared)) + amount;
  2658. var part4 = cubed - squared;
  2659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2665. * @param start defines the start vector
  2666. * @param end defines the end vector
  2667. * @param amount defines the interpolation factor
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Lerp = function (start, end, amount) {
  2671. var x = start.x + ((end.x - start.x) * amount);
  2672. var y = start.y + ((end.y - start.y) * amount);
  2673. return new Vector2(x, y);
  2674. };
  2675. /**
  2676. * Gets the dot product of the vector "left" and the vector "right"
  2677. * @param left defines first vector
  2678. * @param right defines second vector
  2679. * @returns the dot product (float)
  2680. */
  2681. Vector2.Dot = function (left, right) {
  2682. return left.x * right.x + left.y * right.y;
  2683. };
  2684. /**
  2685. * Returns a new Vector2 equal to the normalized given vector
  2686. * @param vector defines the vector to normalize
  2687. * @returns a new Vector2
  2688. */
  2689. Vector2.Normalize = function (vector) {
  2690. var newVector = vector.clone();
  2691. newVector.normalize();
  2692. return newVector;
  2693. };
  2694. /**
  2695. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2696. * @param left defines 1st vector
  2697. * @param right defines 2nd vector
  2698. * @returns a new Vector2
  2699. */
  2700. Vector2.Minimize = function (left, right) {
  2701. var x = (left.x < right.x) ? left.x : right.x;
  2702. var y = (left.y < right.y) ? left.y : right.y;
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2707. * @param left defines 1st vector
  2708. * @param right defines 2nd vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Maximize = function (left, right) {
  2712. var x = (left.x > right.x) ? left.x : right.x;
  2713. var y = (left.y > right.y) ? left.y : right.y;
  2714. return new Vector2(x, y);
  2715. };
  2716. /**
  2717. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2718. * @param vector defines the vector to transform
  2719. * @param transformation defines the matrix to apply
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Transform = function (vector, transformation) {
  2723. var r = Vector2.Zero();
  2724. Vector2.TransformToRef(vector, transformation, r);
  2725. return r;
  2726. };
  2727. /**
  2728. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2729. * @param vector defines the vector to transform
  2730. * @param transformation defines the matrix to apply
  2731. * @param result defines the target vector
  2732. */
  2733. Vector2.TransformToRef = function (vector, transformation, result) {
  2734. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2735. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2736. result.x = x;
  2737. result.y = y;
  2738. };
  2739. /**
  2740. * Determines if a given vector is included in a triangle
  2741. * @param p defines the vector to test
  2742. * @param p0 defines 1st triangle point
  2743. * @param p1 defines 2nd triangle point
  2744. * @param p2 defines 3rd triangle point
  2745. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2746. */
  2747. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2748. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2749. var sign = a < 0 ? -1 : 1;
  2750. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2751. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2752. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2753. };
  2754. /**
  2755. * Gets the distance between the vectors "value1" and "value2"
  2756. * @param value1 defines first vector
  2757. * @param value2 defines second vector
  2758. * @returns the distance between vectors
  2759. */
  2760. Vector2.Distance = function (value1, value2) {
  2761. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2762. };
  2763. /**
  2764. * Returns the squared distance between the vectors "value1" and "value2"
  2765. * @param value1 defines first vector
  2766. * @param value2 defines second vector
  2767. * @returns the squared distance between vectors
  2768. */
  2769. Vector2.DistanceSquared = function (value1, value2) {
  2770. var x = value1.x - value2.x;
  2771. var y = value1.y - value2.y;
  2772. return (x * x) + (y * y);
  2773. };
  2774. /**
  2775. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2776. * @param value1 defines first vector
  2777. * @param value2 defines second vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Center = function (value1, value2) {
  2781. var center = value1.add(value2);
  2782. center.scaleInPlace(0.5);
  2783. return center;
  2784. };
  2785. /**
  2786. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2787. * @param p defines the middle point
  2788. * @param segA defines one point of the segment
  2789. * @param segB defines the other point of the segment
  2790. * @returns the shortest distance
  2791. */
  2792. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2793. var l2 = Vector2.DistanceSquared(segA, segB);
  2794. if (l2 === 0.0) {
  2795. return Vector2.Distance(p, segA);
  2796. }
  2797. var v = segB.subtract(segA);
  2798. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2799. var proj = segA.add(v.multiplyByFloats(t, t));
  2800. return Vector2.Distance(p, proj);
  2801. };
  2802. return Vector2;
  2803. }());
  2804. BABYLON.Vector2 = Vector2;
  2805. /**
  2806. * Classed used to store (x,y,z) vector representation
  2807. * A Vector3 is the main object used in 3D geometry
  2808. * It can represent etiher the coordinates of a point the space, either a direction
  2809. * Reminder: Babylon.js uses a left handed forward facing system
  2810. */
  2811. var Vector3 = /** @class */ (function () {
  2812. /**
  2813. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2814. * @param x defines the first coordinates (on X axis)
  2815. * @param y defines the second coordinates (on Y axis)
  2816. * @param z defines the third coordinates (on Z axis)
  2817. */
  2818. function Vector3(
  2819. /**
  2820. * Defines the first coordinates (on X axis)
  2821. */
  2822. x,
  2823. /**
  2824. * Defines the second coordinates (on Y axis)
  2825. */
  2826. y,
  2827. /**
  2828. * Defines the third coordinates (on Z axis)
  2829. */
  2830. z) {
  2831. if (x === void 0) { x = 0; }
  2832. if (y === void 0) { y = 0; }
  2833. if (z === void 0) { z = 0; }
  2834. this.x = x;
  2835. this.y = y;
  2836. this.z = z;
  2837. }
  2838. /**
  2839. * Creates a string representation of the Vector3
  2840. * @returns a string with the Vector3 coordinates.
  2841. */
  2842. Vector3.prototype.toString = function () {
  2843. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2844. };
  2845. /**
  2846. * Gets the class name
  2847. * @returns the string "Vector3"
  2848. */
  2849. Vector3.prototype.getClassName = function () {
  2850. return "Vector3";
  2851. };
  2852. /**
  2853. * Creates the Vector3 hash code
  2854. * @returns a number which tends to be unique between Vector3 instances
  2855. */
  2856. Vector3.prototype.getHashCode = function () {
  2857. var hash = this.x || 0;
  2858. hash = (hash * 397) ^ (this.y || 0);
  2859. hash = (hash * 397) ^ (this.z || 0);
  2860. return hash;
  2861. };
  2862. // Operators
  2863. /**
  2864. * Creates an array containing three elements : the coordinates of the Vector3
  2865. * @returns a new array of numbers
  2866. */
  2867. Vector3.prototype.asArray = function () {
  2868. var result = [];
  2869. this.toArray(result, 0);
  2870. return result;
  2871. };
  2872. /**
  2873. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2874. * @param array defines the destination array
  2875. * @param index defines the offset in the destination array
  2876. * @returns the current Vector3
  2877. */
  2878. Vector3.prototype.toArray = function (array, index) {
  2879. if (index === void 0) { index = 0; }
  2880. array[index] = this.x;
  2881. array[index + 1] = this.y;
  2882. array[index + 2] = this.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2887. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2888. */
  2889. Vector3.prototype.toQuaternion = function () {
  2890. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2891. };
  2892. /**
  2893. * Adds the given vector to the current Vector3
  2894. * @param otherVector defines the second operand
  2895. * @returns the current updated Vector3
  2896. */
  2897. Vector3.prototype.addInPlace = function (otherVector) {
  2898. this.x += otherVector.x;
  2899. this.y += otherVector.y;
  2900. this.z += otherVector.z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2905. * @param otherVector defines the second operand
  2906. * @returns the resulting Vector3
  2907. */
  2908. Vector3.prototype.add = function (otherVector) {
  2909. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2910. };
  2911. /**
  2912. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2913. * @param otherVector defines the second operand
  2914. * @param result defines the Vector3 object where to store the result
  2915. * @returns the current Vector3
  2916. */
  2917. Vector3.prototype.addToRef = function (otherVector, result) {
  2918. result.x = this.x + otherVector.x;
  2919. result.y = this.y + otherVector.y;
  2920. result.z = this.z + otherVector.z;
  2921. return this;
  2922. };
  2923. /**
  2924. * Subtract the given vector from the current Vector3
  2925. * @param otherVector defines the second operand
  2926. * @returns the current updated Vector3
  2927. */
  2928. Vector3.prototype.subtractInPlace = function (otherVector) {
  2929. this.x -= otherVector.x;
  2930. this.y -= otherVector.y;
  2931. this.z -= otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the resulting Vector3
  2938. */
  2939. Vector3.prototype.subtract = function (otherVector) {
  2940. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2941. };
  2942. /**
  2943. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2944. * @param otherVector defines the second operand
  2945. * @param result defines the Vector3 object where to store the result
  2946. * @returns the current Vector3
  2947. */
  2948. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2949. result.x = this.x - otherVector.x;
  2950. result.y = this.y - otherVector.y;
  2951. result.z = this.z - otherVector.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2956. * @param x defines the x coordinate of the operand
  2957. * @param y defines the y coordinate of the operand
  2958. * @param z defines the z coordinate of the operand
  2959. * @returns the resulting Vector3
  2960. */
  2961. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2962. return new Vector3(this.x - x, this.y - y, this.z - z);
  2963. };
  2964. /**
  2965. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2966. * @param x defines the x coordinate of the operand
  2967. * @param y defines the y coordinate of the operand
  2968. * @param z defines the z coordinate of the operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2973. result.x = this.x - x;
  2974. result.y = this.y - y;
  2975. result.z = this.z - z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2980. * @returns a new Vector3
  2981. */
  2982. Vector3.prototype.negate = function () {
  2983. return new Vector3(-this.x, -this.y, -this.z);
  2984. };
  2985. /**
  2986. * Multiplies the Vector3 coordinates by the float "scale"
  2987. * @param scale defines the multiplier factor
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.scaleInPlace = function (scale) {
  2991. this.x *= scale;
  2992. this.y *= scale;
  2993. this.z *= scale;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2998. * @param scale defines the multiplier factor
  2999. * @returns a new Vector3
  3000. */
  3001. Vector3.prototype.scale = function (scale) {
  3002. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3006. * @param scale defines the multiplier factor
  3007. * @param result defines the Vector3 object where to store the result
  3008. * @returns the current Vector3
  3009. */
  3010. Vector3.prototype.scaleToRef = function (scale, result) {
  3011. result.x = this.x * scale;
  3012. result.y = this.y * scale;
  3013. result.z = this.z * scale;
  3014. return this;
  3015. };
  3016. /**
  3017. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3018. * @param scale defines the scale factor
  3019. * @param result defines the Vector3 object where to store the result
  3020. * @returns the unmodified current Vector3
  3021. */
  3022. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3023. result.x += this.x * scale;
  3024. result.y += this.y * scale;
  3025. result.z += this.z * scale;
  3026. return this;
  3027. };
  3028. /**
  3029. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3030. * @param otherVector defines the second operand
  3031. * @returns true if both vectors are equals
  3032. */
  3033. Vector3.prototype.equals = function (otherVector) {
  3034. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3035. };
  3036. /**
  3037. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3038. * @param otherVector defines the second operand
  3039. * @param epsilon defines the minimal distance to define values as equals
  3040. * @returns true if both vectors are distant less than epsilon
  3041. */
  3042. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3043. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3044. 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);
  3045. };
  3046. /**
  3047. * Returns true if the current Vector3 coordinates equals the given floats
  3048. * @param x defines the x coordinate of the operand
  3049. * @param y defines the y coordinate of the operand
  3050. * @param z defines the z coordinate of the operand
  3051. * @returns true if both vectors are equals
  3052. */
  3053. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3054. return this.x === x && this.y === y && this.z === z;
  3055. };
  3056. /**
  3057. * Multiplies the current Vector3 coordinates by the given ones
  3058. * @param otherVector defines the second operand
  3059. * @returns the current updated Vector3
  3060. */
  3061. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3062. this.x *= otherVector.x;
  3063. this.y *= otherVector.y;
  3064. this.z *= otherVector.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3069. * @param otherVector defines the second operand
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.multiply = function (otherVector) {
  3073. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3074. };
  3075. /**
  3076. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3077. * @param otherVector defines the second operand
  3078. * @param result defines the Vector3 object where to store the result
  3079. * @returns the current Vector3
  3080. */
  3081. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3082. result.x = this.x * otherVector.x;
  3083. result.y = this.y * otherVector.y;
  3084. result.z = this.z * otherVector.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3095. return new Vector3(this.x * x, this.y * y, this.z * z);
  3096. };
  3097. /**
  3098. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.divide = function (otherVector) {
  3103. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3104. };
  3105. /**
  3106. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.divideToRef = function (otherVector, result) {
  3112. result.x = this.x / otherVector.x;
  3113. result.y = this.y / otherVector.y;
  3114. result.z = this.z / otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Divides the current Vector3 coordinates by the given ones.
  3119. * @param otherVector defines the second operand
  3120. * @returns the current updated Vector3
  3121. */
  3122. Vector3.prototype.divideInPlace = function (otherVector) {
  3123. return this.divideToRef(otherVector, this);
  3124. };
  3125. /**
  3126. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3127. * @param other defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.minimizeInPlace = function (other) {
  3131. if (other.x < this.x)
  3132. this.x = other.x;
  3133. if (other.y < this.y)
  3134. this.y = other.y;
  3135. if (other.z < this.z)
  3136. this.z = other.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3141. * @param other defines the second operand
  3142. * @returns the current updated Vector3
  3143. */
  3144. Vector3.prototype.maximizeInPlace = function (other) {
  3145. if (other.x > this.x)
  3146. this.x = other.x;
  3147. if (other.y > this.y)
  3148. this.y = other.y;
  3149. if (other.z > this.z)
  3150. this.z = other.z;
  3151. return this;
  3152. };
  3153. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3154. /**
  3155. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3156. */
  3157. get: function () {
  3158. var absX = Math.abs(this.x);
  3159. var absY = Math.abs(this.y);
  3160. if (absX !== absY) {
  3161. return true;
  3162. }
  3163. var absZ = Math.abs(this.z);
  3164. if (absX !== absZ) {
  3165. return true;
  3166. }
  3167. if (absY !== absZ) {
  3168. return true;
  3169. }
  3170. return false;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. /**
  3176. * Gets a new Vector3 from current Vector3 floored values
  3177. * @returns a new Vector3
  3178. */
  3179. Vector3.prototype.floor = function () {
  3180. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3181. };
  3182. /**
  3183. * Gets a new Vector3 from current Vector3 floored values
  3184. * @returns a new Vector3
  3185. */
  3186. Vector3.prototype.fract = function () {
  3187. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3188. };
  3189. // Properties
  3190. /**
  3191. * Gets the length of the Vector3
  3192. * @returns the length of the Vecto3
  3193. */
  3194. Vector3.prototype.length = function () {
  3195. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3196. };
  3197. /**
  3198. * Gets the squared length of the Vector3
  3199. * @returns squared length of the Vector3
  3200. */
  3201. Vector3.prototype.lengthSquared = function () {
  3202. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3203. };
  3204. /**
  3205. * Normalize the current Vector3.
  3206. * Please note that this is an in place operation.
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.normalize = function () {
  3210. var len = this.length();
  3211. if (len === 0 || len === 1.0)
  3212. return this;
  3213. var num = 1.0 / len;
  3214. this.x *= num;
  3215. this.y *= num;
  3216. this.z *= num;
  3217. return this;
  3218. };
  3219. /**
  3220. * Normalize the current Vector3 to a new vector
  3221. * @returns the new Vector3
  3222. */
  3223. Vector3.prototype.normalizeToNew = function () {
  3224. var normalized = new Vector3(0, 0, 0);
  3225. this.normalizeToRef(normalized);
  3226. return normalized;
  3227. };
  3228. /**
  3229. * Normalize the current Vector3 to the reference
  3230. * @param reference define the Vector3 to update
  3231. * @returns the updated Vector3
  3232. */
  3233. Vector3.prototype.normalizeToRef = function (reference) {
  3234. var len = this.length();
  3235. if (len === 0 || len === 1.0) {
  3236. reference.set(this.x, this.y, this.z);
  3237. return reference;
  3238. }
  3239. var scale = 1.0 / len;
  3240. this.scaleToRef(scale, reference);
  3241. return reference;
  3242. };
  3243. /**
  3244. * Creates a new Vector3 copied from the current Vector3
  3245. * @returns the new Vector3
  3246. */
  3247. Vector3.prototype.clone = function () {
  3248. return new Vector3(this.x, this.y, this.z);
  3249. };
  3250. /**
  3251. * Copies the given vector coordinates to the current Vector3 ones
  3252. * @param source defines the source Vector3
  3253. * @returns the current updated Vector3
  3254. */
  3255. Vector3.prototype.copyFrom = function (source) {
  3256. this.x = source.x;
  3257. this.y = source.y;
  3258. this.z = source.z;
  3259. return this;
  3260. };
  3261. /**
  3262. * Copies the given floats to the current Vector3 coordinates
  3263. * @param x defines the x coordinate of the operand
  3264. * @param y defines the y coordinate of the operand
  3265. * @param z defines the z coordinate of the operand
  3266. * @returns the current updated Vector3
  3267. */
  3268. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3269. this.x = x;
  3270. this.y = y;
  3271. this.z = z;
  3272. return this;
  3273. };
  3274. /**
  3275. * Copies the given floats to the current Vector3 coordinates
  3276. * @param x defines the x coordinate of the operand
  3277. * @param y defines the y coordinate of the operand
  3278. * @param z defines the z coordinate of the operand
  3279. * @returns the current updated Vector3
  3280. */
  3281. Vector3.prototype.set = function (x, y, z) {
  3282. return this.copyFromFloats(x, y, z);
  3283. };
  3284. // Statics
  3285. /**
  3286. * Get the clip factor between two vectors
  3287. * @param vector0 defines the first operand
  3288. * @param vector1 defines the second operand
  3289. * @param axis defines the axis to use
  3290. * @param size defines the size along the axis
  3291. * @returns the clip factor
  3292. */
  3293. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3294. var d0 = Vector3.Dot(vector0, axis) - size;
  3295. var d1 = Vector3.Dot(vector1, axis) - size;
  3296. var s = d0 / (d0 - d1);
  3297. return s;
  3298. };
  3299. /**
  3300. * Get angle between two vectors
  3301. * @param vector0 angle between vector0 and vector1
  3302. * @param vector1 angle between vector0 and vector1
  3303. * @param normal direction of the normal
  3304. * @return the angle between vector0 and vector1
  3305. */
  3306. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3307. var v0 = vector0.clone().normalize();
  3308. var v1 = vector1.clone().normalize();
  3309. var dot = Vector3.Dot(v0, v1);
  3310. var n = Vector3.Cross(v0, v1);
  3311. if (Vector3.Dot(n, normal) > 0) {
  3312. return Math.acos(dot);
  3313. }
  3314. return -Math.acos(dot);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set from the index "offset" of the given array
  3318. * @param array defines the source array
  3319. * @param offset defines the offset in the source array
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.FromArray = function (array, offset) {
  3323. if (!offset) {
  3324. offset = 0;
  3325. }
  3326. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3330. * This function is deprecated. Use FromArray instead
  3331. * @param array defines the source array
  3332. * @param offset defines the offset in the source array
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.FromFloatArray = function (array, offset) {
  3336. return Vector3.FromArray(array, offset);
  3337. };
  3338. /**
  3339. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3340. * @param array defines the source array
  3341. * @param offset defines the offset in the source array
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.FromArrayToRef = function (array, offset, result) {
  3345. result.x = array[offset];
  3346. result.y = array[offset + 1];
  3347. result.z = array[offset + 2];
  3348. };
  3349. /**
  3350. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArrayToRef instead.
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @param result defines the Vector3 where to store the result
  3355. */
  3356. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3357. return Vector3.FromArrayToRef(array, offset, result);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the given floats.
  3361. * @param x defines the x coordinate of the source
  3362. * @param y defines the y coordinate of the source
  3363. * @param z defines the z coordinate of the source
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3367. result.x = x;
  3368. result.y = y;
  3369. result.z = z;
  3370. };
  3371. /**
  3372. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3373. * @returns a new empty Vector3
  3374. */
  3375. Vector3.Zero = function () {
  3376. return new Vector3(0.0, 0.0, 0.0);
  3377. };
  3378. /**
  3379. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3380. * @returns a new unit Vector3
  3381. */
  3382. Vector3.One = function () {
  3383. return new Vector3(1.0, 1.0, 1.0);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3387. * @returns a new up Vector3
  3388. */
  3389. Vector3.Up = function () {
  3390. return new Vector3(0.0, 1.0, 0.0);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3394. * @returns a new down Vector3
  3395. */
  3396. Vector3.Down = function () {
  3397. return new Vector3(0.0, -1.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3401. * @returns a new forward Vector3
  3402. */
  3403. Vector3.Forward = function () {
  3404. return new Vector3(0.0, 0.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3408. * @returns a new right Vector3
  3409. */
  3410. Vector3.Right = function () {
  3411. return new Vector3(1.0, 0.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3415. * @returns a new left Vector3
  3416. */
  3417. Vector3.Left = function () {
  3418. return new Vector3(-1.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3422. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3423. * @param vector defines the Vector3 to transform
  3424. * @param transformation defines the transformation matrix
  3425. * @returns the transformed Vector3
  3426. */
  3427. Vector3.TransformCoordinates = function (vector, transformation) {
  3428. var result = Vector3.Zero();
  3429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3430. return result;
  3431. };
  3432. /**
  3433. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3443. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3444. result.x = x / w;
  3445. result.y = y / w;
  3446. result.z = z / w;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3450. * This method computes tranformed coordinates only, not transformed direction vectors
  3451. * @param x define the x coordinate of the source vector
  3452. * @param y define the y coordinate of the source vector
  3453. * @param z define the z coordinate of the source vector
  3454. * @param transformation defines the transformation matrix
  3455. * @param result defines the Vector3 where to store the result
  3456. */
  3457. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3458. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3459. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3460. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3461. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3462. result.x = rx / rw;
  3463. result.y = ry / rw;
  3464. result.z = rz / rw;
  3465. };
  3466. /**
  3467. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param vector defines the Vector3 to transform
  3470. * @param transformation defines the transformation matrix
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.TransformNormal = function (vector, transformation) {
  3474. var result = Vector3.Zero();
  3475. Vector3.TransformNormalToRef(vector, transformation, result);
  3476. return result;
  3477. };
  3478. /**
  3479. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3486. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3487. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3488. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3489. result.x = x;
  3490. result.y = y;
  3491. result.z = z;
  3492. };
  3493. /**
  3494. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3495. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3496. * @param x define the x coordinate of the source vector
  3497. * @param y define the y coordinate of the source vector
  3498. * @param z define the z coordinate of the source vector
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3503. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3504. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3505. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3506. };
  3507. /**
  3508. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3509. * @param value1 defines the first control point
  3510. * @param value2 defines the second control point
  3511. * @param value3 defines the third control point
  3512. * @param value4 defines the fourth control point
  3513. * @param amount defines the amount on the spline to use
  3514. * @returns the new Vector3
  3515. */
  3516. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3517. var squared = amount * amount;
  3518. var cubed = amount * squared;
  3519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3525. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3526. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3527. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3528. return new Vector3(x, y, z);
  3529. };
  3530. /**
  3531. * 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"
  3532. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3533. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3534. * @param value defines the current value
  3535. * @param min defines the lower range value
  3536. * @param max defines the upper range value
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Clamp = function (value, min, max) {
  3540. var x = value.x;
  3541. x = (x > max.x) ? max.x : x;
  3542. x = (x < min.x) ? min.x : x;
  3543. var y = value.y;
  3544. y = (y > max.y) ? max.y : y;
  3545. y = (y < min.y) ? min.y : y;
  3546. var z = value.z;
  3547. z = (z > max.z) ? max.z : z;
  3548. z = (z < min.z) ? min.z : z;
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3553. * @param value1 defines the first control point
  3554. * @param tangent1 defines the first tangent vector
  3555. * @param value2 defines the second control point
  3556. * @param tangent2 defines the second tangent vector
  3557. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3561. var squared = amount * amount;
  3562. var cubed = amount * squared;
  3563. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3564. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3565. var part3 = (cubed - (2.0 * squared)) + amount;
  3566. var part4 = cubed - squared;
  3567. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3568. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3569. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3574. * @param start defines the start value
  3575. * @param end defines the end value
  3576. * @param amount max defines amount between both (between 0 and 1)
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.Lerp = function (start, end, amount) {
  3580. var result = new Vector3(0, 0, 0);
  3581. Vector3.LerpToRef(start, end, amount, result);
  3582. return result;
  3583. };
  3584. /**
  3585. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.LerpToRef = function (start, end, amount, result) {
  3592. result.x = start.x + ((end.x - start.x) * amount);
  3593. result.y = start.y + ((end.y - start.y) * amount);
  3594. result.z = start.z + ((end.z - start.z) * amount);
  3595. };
  3596. /**
  3597. * Returns the dot product (float) between the vectors "left" and "right"
  3598. * @param left defines the left operand
  3599. * @param right defines the right operand
  3600. * @returns the dot product
  3601. */
  3602. Vector3.Dot = function (left, right) {
  3603. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3604. };
  3605. /**
  3606. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3607. * The cross product is then orthogonal to both "left" and "right"
  3608. * @param left defines the left operand
  3609. * @param right defines the right operand
  3610. * @returns the cross product
  3611. */
  3612. Vector3.Cross = function (left, right) {
  3613. var result = Vector3.Zero();
  3614. Vector3.CrossToRef(left, right, result);
  3615. return result;
  3616. };
  3617. /**
  3618. * Sets the given vector "result" with the cross product of "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @param result defines the Vector3 where to store the result
  3623. */
  3624. Vector3.CrossToRef = function (left, right, result) {
  3625. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3626. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3627. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3628. result.copyFrom(MathTmp.Vector3[0]);
  3629. };
  3630. /**
  3631. * Returns a new Vector3 as the normalization of the given vector
  3632. * @param vector defines the Vector3 to normalize
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Normalize = function (vector) {
  3636. var result = Vector3.Zero();
  3637. Vector3.NormalizeToRef(vector, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the normalization of the given first vector
  3642. * @param vector defines the Vector3 to normalize
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.NormalizeToRef = function (vector, result) {
  3646. result.copyFrom(vector);
  3647. result.normalize();
  3648. };
  3649. /**
  3650. * Project a Vector3 onto screen space
  3651. * @param vector defines the Vector3 to project
  3652. * @param world defines the world matrix to use
  3653. * @param transform defines the transform (view x projection) matrix to use
  3654. * @param viewport defines the screen viewport to use
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Project = function (vector, world, transform, viewport) {
  3658. var cw = viewport.width;
  3659. var ch = viewport.height;
  3660. var cx = viewport.x;
  3661. var cy = viewport.y;
  3662. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3663. 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);
  3664. var matrix = MathTmp.Matrix[0];
  3665. world.multiplyToRef(transform, matrix);
  3666. matrix.multiplyToRef(viewportMatrix, matrix);
  3667. return Vector3.TransformCoordinates(vector, matrix);
  3668. };
  3669. /**
  3670. * Unproject from screen space to object space
  3671. * @param source defines the screen space Vector3 to use
  3672. * @param viewportWidth defines the current width of the viewport
  3673. * @param viewportHeight defines the current height of the viewport
  3674. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3675. * @param transform defines the transform (view x projection) matrix to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3679. var matrix = MathTmp.Matrix[0];
  3680. world.multiplyToRef(transform, matrix);
  3681. matrix.invert();
  3682. source.x = source.x / viewportWidth * 2 - 1;
  3683. source.y = -(source.y / viewportHeight * 2 - 1);
  3684. var vector = Vector3.TransformCoordinates(source, matrix);
  3685. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3686. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3687. vector = vector.scale(1.0 / num);
  3688. }
  3689. return vector;
  3690. };
  3691. /**
  3692. * Unproject from screen space to object space
  3693. * @param source defines the screen space Vector3 to use
  3694. * @param viewportWidth defines the current width of the viewport
  3695. * @param viewportHeight defines the current height of the viewport
  3696. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3697. * @param view defines the view matrix to use
  3698. * @param projection defines the projection matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3702. var result = Vector3.Zero();
  3703. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3704. return result;
  3705. };
  3706. /**
  3707. * Unproject from screen space to object space
  3708. * @param source defines the screen space Vector3 to use
  3709. * @param viewportWidth defines the current width of the viewport
  3710. * @param viewportHeight defines the current height of the viewport
  3711. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3712. * @param view defines the view matrix to use
  3713. * @param projection defines the projection matrix to use
  3714. * @param result defines the Vector3 where to store the result
  3715. */
  3716. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3717. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param sourceX defines the screen space x coordinate to use
  3722. * @param sourceY defines the screen space y coordinate to use
  3723. * @param sourceZ defines the screen space z coordinate to use
  3724. * @param viewportWidth defines the current width of the viewport
  3725. * @param viewportHeight defines the current height of the viewport
  3726. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3727. * @param view defines the view matrix to use
  3728. * @param projection defines the projection matrix to use
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3732. var matrix = MathTmp.Matrix[0];
  3733. world.multiplyToRef(view, matrix);
  3734. matrix.multiplyToRef(projection, matrix);
  3735. matrix.invert();
  3736. var screenSource = MathTmp.Vector3[0];
  3737. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3738. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3739. screenSource.z = 2 * sourceZ - 1.0;
  3740. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3741. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3742. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3743. result.scaleInPlace(1.0 / num);
  3744. }
  3745. };
  3746. /**
  3747. * Gets the minimal coordinate values between two Vector3
  3748. * @param left defines the first operand
  3749. * @param right defines the second operand
  3750. * @returns the new Vector3
  3751. */
  3752. Vector3.Minimize = function (left, right) {
  3753. var min = left.clone();
  3754. min.minimizeInPlace(right);
  3755. return min;
  3756. };
  3757. /**
  3758. * Gets the maximal coordinate values between two Vector3
  3759. * @param left defines the first operand
  3760. * @param right defines the second operand
  3761. * @returns the new Vector3
  3762. */
  3763. Vector3.Maximize = function (left, right) {
  3764. var max = left.clone();
  3765. max.maximizeInPlace(right);
  3766. return max;
  3767. };
  3768. /**
  3769. * Returns the distance between the vectors "value1" and "value2"
  3770. * @param value1 defines the first operand
  3771. * @param value2 defines the second operand
  3772. * @returns the distance
  3773. */
  3774. Vector3.Distance = function (value1, value2) {
  3775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3776. };
  3777. /**
  3778. * Returns the squared distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the squared distance
  3782. */
  3783. Vector3.DistanceSquared = function (value1, value2) {
  3784. var x = value1.x - value2.x;
  3785. var y = value1.y - value2.y;
  3786. var z = value1.z - value2.z;
  3787. return (x * x) + (y * y) + (z * z);
  3788. };
  3789. /**
  3790. * Returns a new Vector3 located at the center between "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the new Vector3
  3794. */
  3795. Vector3.Center = function (value1, value2) {
  3796. var center = value1.add(value2);
  3797. center.scaleInPlace(0.5);
  3798. return center;
  3799. };
  3800. /**
  3801. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3802. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3803. * to something in order to rotate it from its local system to the given target system
  3804. * Note: axis1, axis2 and axis3 are normalized during this operation
  3805. * @param axis1 defines the first axis
  3806. * @param axis2 defines the second axis
  3807. * @param axis3 defines the third axis
  3808. * @returns a new Vector3
  3809. */
  3810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3811. var rotation = Vector3.Zero();
  3812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3813. return rotation;
  3814. };
  3815. /**
  3816. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @param ref defines the Vector3 where to store the result
  3821. */
  3822. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3823. var quat = MathTmp.Quaternion[0];
  3824. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3825. quat.toEulerAnglesToRef(ref);
  3826. };
  3827. return Vector3;
  3828. }());
  3829. BABYLON.Vector3 = Vector3;
  3830. //Vector4 class created for EulerAngle class conversion to Quaternion
  3831. var Vector4 = /** @class */ (function () {
  3832. /**
  3833. * Creates a Vector4 object from the given floats.
  3834. */
  3835. function Vector4(x, y, z, w) {
  3836. this.x = x;
  3837. this.y = y;
  3838. this.z = z;
  3839. this.w = w;
  3840. }
  3841. /**
  3842. * Returns the string with the Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.toString = function () {
  3845. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3846. };
  3847. /**
  3848. * Returns the string "Vector4".
  3849. */
  3850. Vector4.prototype.getClassName = function () {
  3851. return "Vector4";
  3852. };
  3853. /**
  3854. * Returns the Vector4 hash code.
  3855. */
  3856. Vector4.prototype.getHashCode = function () {
  3857. var hash = this.x || 0;
  3858. hash = (hash * 397) ^ (this.y || 0);
  3859. hash = (hash * 397) ^ (this.z || 0);
  3860. hash = (hash * 397) ^ (this.w || 0);
  3861. return hash;
  3862. };
  3863. // Operators
  3864. /**
  3865. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.asArray = function () {
  3868. var result = new Array();
  3869. this.toArray(result, 0);
  3870. return result;
  3871. };
  3872. /**
  3873. * Populates the given array from the given index with the Vector4 coordinates.
  3874. * Returns the Vector4.
  3875. */
  3876. Vector4.prototype.toArray = function (array, index) {
  3877. if (index === undefined) {
  3878. index = 0;
  3879. }
  3880. array[index] = this.x;
  3881. array[index + 1] = this.y;
  3882. array[index + 2] = this.z;
  3883. array[index + 3] = this.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Adds the given vector to the current Vector4.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.addInPlace = function (otherVector) {
  3891. this.x += otherVector.x;
  3892. this.y += otherVector.y;
  3893. this.z += otherVector.z;
  3894. this.w += otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3899. */
  3900. Vector4.prototype.add = function (otherVector) {
  3901. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3902. };
  3903. /**
  3904. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3905. * Returns the current Vector4.
  3906. */
  3907. Vector4.prototype.addToRef = function (otherVector, result) {
  3908. result.x = this.x + otherVector.x;
  3909. result.y = this.y + otherVector.y;
  3910. result.z = this.z + otherVector.z;
  3911. result.w = this.w + otherVector.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Subtract in place the given vector from the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.subtractInPlace = function (otherVector) {
  3919. this.x -= otherVector.x;
  3920. this.y -= otherVector.y;
  3921. this.z -= otherVector.z;
  3922. this.w -= otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3927. */
  3928. Vector4.prototype.subtract = function (otherVector) {
  3929. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3930. };
  3931. /**
  3932. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3936. result.x = this.x - otherVector.x;
  3937. result.y = this.y - otherVector.y;
  3938. result.z = this.z - otherVector.z;
  3939. result.w = this.w - otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3946. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3947. };
  3948. /**
  3949. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3950. * Returns the current Vector4.
  3951. */
  3952. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3953. result.x = this.x - x;
  3954. result.y = this.y - y;
  3955. result.z = this.z - z;
  3956. result.w = this.w - w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3961. */
  3962. Vector4.prototype.negate = function () {
  3963. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3964. };
  3965. /**
  3966. * Multiplies the current Vector4 coordinates by scale (float).
  3967. * Returns the updated Vector4.
  3968. */
  3969. Vector4.prototype.scaleInPlace = function (scale) {
  3970. this.x *= scale;
  3971. this.y *= scale;
  3972. this.z *= scale;
  3973. this.w *= scale;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3978. */
  3979. Vector4.prototype.scale = function (scale) {
  3980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3981. };
  3982. /**
  3983. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3984. * Returns the current Vector4.
  3985. */
  3986. Vector4.prototype.scaleToRef = function (scale, result) {
  3987. result.x = this.x * scale;
  3988. result.y = this.y * scale;
  3989. result.z = this.z * scale;
  3990. result.w = this.w * scale;
  3991. return this;
  3992. };
  3993. /**
  3994. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3995. * @param scale defines the scale factor
  3996. * @param result defines the Vector4 object where to store the result
  3997. * @returns the unmodified current Vector4
  3998. */
  3999. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4000. result.x += this.x * scale;
  4001. result.y += this.y * scale;
  4002. result.z += this.z * scale;
  4003. result.w += this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4008. */
  4009. Vector4.prototype.equals = function (otherVector) {
  4010. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4011. };
  4012. /**
  4013. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4014. */
  4015. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4017. return otherVector
  4018. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4019. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4020. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4021. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4022. };
  4023. /**
  4024. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4025. */
  4026. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4027. return this.x === x && this.y === y && this.z === z && this.w === w;
  4028. };
  4029. /**
  4030. * Multiplies in place the current Vector4 by the given one.
  4031. * Returns the updated Vector4.
  4032. */
  4033. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4034. this.x *= otherVector.x;
  4035. this.y *= otherVector.y;
  4036. this.z *= otherVector.z;
  4037. this.w *= otherVector.w;
  4038. return this;
  4039. };
  4040. /**
  4041. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4042. */
  4043. Vector4.prototype.multiply = function (otherVector) {
  4044. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4045. };
  4046. /**
  4047. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4048. * Returns the current Vector4.
  4049. */
  4050. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4051. result.x = this.x * otherVector.x;
  4052. result.y = this.y * otherVector.y;
  4053. result.z = this.z * otherVector.z;
  4054. result.w = this.w * otherVector.w;
  4055. return this;
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4059. */
  4060. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4061. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4065. */
  4066. Vector4.prototype.divide = function (otherVector) {
  4067. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.divideToRef = function (otherVector, result) {
  4074. result.x = this.x / otherVector.x;
  4075. result.y = this.y / otherVector.y;
  4076. result.z = this.z / otherVector.z;
  4077. result.w = this.w / otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Divides the current Vector3 coordinates by the given ones.
  4082. * @returns the updated Vector3.
  4083. */
  4084. Vector4.prototype.divideInPlace = function (otherVector) {
  4085. return this.divideToRef(otherVector, this);
  4086. };
  4087. /**
  4088. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4089. * @param other defines the second operand
  4090. * @returns the current updated Vector4
  4091. */
  4092. Vector4.prototype.minimizeInPlace = function (other) {
  4093. if (other.x < this.x)
  4094. this.x = other.x;
  4095. if (other.y < this.y)
  4096. this.y = other.y;
  4097. if (other.z < this.z)
  4098. this.z = other.z;
  4099. if (other.w < this.w)
  4100. this.w = other.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.maximizeInPlace = function (other) {
  4109. if (other.x > this.x)
  4110. this.x = other.x;
  4111. if (other.y > this.y)
  4112. this.y = other.y;
  4113. if (other.z > this.z)
  4114. this.z = other.z;
  4115. if (other.w > this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Gets a new Vector4 from current Vector4 floored values
  4121. * @returns a new Vector4
  4122. */
  4123. Vector4.prototype.floor = function () {
  4124. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4125. };
  4126. /**
  4127. * Gets a new Vector4 from current Vector3 floored values
  4128. * @returns a new Vector4
  4129. */
  4130. Vector4.prototype.fract = function () {
  4131. 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));
  4132. };
  4133. // Properties
  4134. /**
  4135. * Returns the Vector4 length (float).
  4136. */
  4137. Vector4.prototype.length = function () {
  4138. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. /**
  4141. * Returns the Vector4 squared length (float).
  4142. */
  4143. Vector4.prototype.lengthSquared = function () {
  4144. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4145. };
  4146. // Methods
  4147. /**
  4148. * Normalizes in place the Vector4.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.normalize = function () {
  4152. var len = this.length();
  4153. if (len === 0)
  4154. return this;
  4155. var num = 1.0 / len;
  4156. this.x *= num;
  4157. this.y *= num;
  4158. this.z *= num;
  4159. this.w *= num;
  4160. return this;
  4161. };
  4162. /**
  4163. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4164. */
  4165. Vector4.prototype.toVector3 = function () {
  4166. return new Vector3(this.x, this.y, this.z);
  4167. };
  4168. /**
  4169. * Returns a new Vector4 copied from the current one.
  4170. */
  4171. Vector4.prototype.clone = function () {
  4172. return new Vector4(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Vector4 with the given one coordinates.
  4176. * Returns the updated Vector4.
  4177. */
  4178. Vector4.prototype.copyFrom = function (source) {
  4179. this.x = source.x;
  4180. this.y = source.y;
  4181. this.z = source.z;
  4182. this.w = source.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Vector4 coordinates with the given floats.
  4187. * Returns the updated Vector4.
  4188. */
  4189. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Vector4 coordinates with the given floats.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. // Statics
  4204. /**
  4205. * Returns a new Vector4 set from the starting index of the given array.
  4206. */
  4207. Vector4.FromArray = function (array, offset) {
  4208. if (!offset) {
  4209. offset = 0;
  4210. }
  4211. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4212. };
  4213. /**
  4214. * Updates the given vector "result" from the starting index of the given array.
  4215. */
  4216. Vector4.FromArrayToRef = function (array, offset, result) {
  4217. result.x = array[offset];
  4218. result.y = array[offset + 1];
  4219. result.z = array[offset + 2];
  4220. result.w = array[offset + 3];
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given Float32Array.
  4224. */
  4225. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4226. Vector4.FromArrayToRef(array, offset, result);
  4227. };
  4228. /**
  4229. * Updates the given vector "result" coordinates from the given floats.
  4230. */
  4231. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4232. result.x = x;
  4233. result.y = y;
  4234. result.z = z;
  4235. result.w = w;
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4239. */
  4240. Vector4.Zero = function () {
  4241. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4242. };
  4243. /**
  4244. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4245. */
  4246. Vector4.One = function () {
  4247. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4248. };
  4249. /**
  4250. * Returns a new normalized Vector4 from the given one.
  4251. */
  4252. Vector4.Normalize = function (vector) {
  4253. var result = Vector4.Zero();
  4254. Vector4.NormalizeToRef(vector, result);
  4255. return result;
  4256. };
  4257. /**
  4258. * Updates the given vector "result" from the normalization of the given one.
  4259. */
  4260. Vector4.NormalizeToRef = function (vector, result) {
  4261. result.copyFrom(vector);
  4262. result.normalize();
  4263. };
  4264. Vector4.Minimize = function (left, right) {
  4265. var min = left.clone();
  4266. min.minimizeInPlace(right);
  4267. return min;
  4268. };
  4269. Vector4.Maximize = function (left, right) {
  4270. var max = left.clone();
  4271. max.maximizeInPlace(right);
  4272. return max;
  4273. };
  4274. /**
  4275. * Returns the distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.Distance = function (value1, value2) {
  4278. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4279. };
  4280. /**
  4281. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4282. */
  4283. Vector4.DistanceSquared = function (value1, value2) {
  4284. var x = value1.x - value2.x;
  4285. var y = value1.y - value2.y;
  4286. var z = value1.z - value2.z;
  4287. var w = value1.w - value2.w;
  4288. return (x * x) + (y * y) + (z * z) + (w * w);
  4289. };
  4290. /**
  4291. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4292. */
  4293. Vector4.Center = function (value1, value2) {
  4294. var center = value1.add(value2);
  4295. center.scaleInPlace(0.5);
  4296. return center;
  4297. };
  4298. /**
  4299. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4300. * This methods computes transformed normalized direction vectors only.
  4301. */
  4302. Vector4.TransformNormal = function (vector, transformation) {
  4303. var result = Vector4.Zero();
  4304. Vector4.TransformNormalToRef(vector, transformation, result);
  4305. return result;
  4306. };
  4307. /**
  4308. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4312. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4313. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4314. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4315. result.x = x;
  4316. result.y = y;
  4317. result.z = z;
  4318. result.w = vector.w;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4325. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4326. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4327. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4328. result.w = w;
  4329. };
  4330. return Vector4;
  4331. }());
  4332. BABYLON.Vector4 = Vector4;
  4333. var Size = /** @class */ (function () {
  4334. /**
  4335. * Creates a Size object from the given width and height (floats).
  4336. */
  4337. function Size(width, height) {
  4338. this.width = width;
  4339. this.height = height;
  4340. }
  4341. // Returns a string with the Size width and height.
  4342. Size.prototype.toString = function () {
  4343. return "{W: " + this.width + ", H: " + this.height + "}";
  4344. };
  4345. /**
  4346. * Returns the string "Size"
  4347. */
  4348. Size.prototype.getClassName = function () {
  4349. return "Size";
  4350. };
  4351. /**
  4352. * Returns the Size hash code.
  4353. */
  4354. Size.prototype.getHashCode = function () {
  4355. var hash = this.width || 0;
  4356. hash = (hash * 397) ^ (this.height || 0);
  4357. return hash;
  4358. };
  4359. /**
  4360. * Updates the current size from the given one.
  4361. * Returns the updated Size.
  4362. */
  4363. Size.prototype.copyFrom = function (src) {
  4364. this.width = src.width;
  4365. this.height = src.height;
  4366. };
  4367. /**
  4368. * Updates in place the current Size from the given floats.
  4369. * Returns the updated Size.
  4370. */
  4371. Size.prototype.copyFromFloats = function (width, height) {
  4372. this.width = width;
  4373. this.height = height;
  4374. return this;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.set = function (width, height) {
  4381. return this.copyFromFloats(width, height);
  4382. };
  4383. /**
  4384. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4385. */
  4386. Size.prototype.multiplyByFloats = function (w, h) {
  4387. return new Size(this.width * w, this.height * h);
  4388. };
  4389. /**
  4390. * Returns a new Size copied from the given one.
  4391. */
  4392. Size.prototype.clone = function () {
  4393. return new Size(this.width, this.height);
  4394. };
  4395. /**
  4396. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4397. */
  4398. Size.prototype.equals = function (other) {
  4399. if (!other) {
  4400. return false;
  4401. }
  4402. return (this.width === other.width) && (this.height === other.height);
  4403. };
  4404. Object.defineProperty(Size.prototype, "surface", {
  4405. /**
  4406. * Returns the surface of the Size : width * height (float).
  4407. */
  4408. get: function () {
  4409. return this.width * this.height;
  4410. },
  4411. enumerable: true,
  4412. configurable: true
  4413. });
  4414. /**
  4415. * Returns a new Size set to (0.0, 0.0)
  4416. */
  4417. Size.Zero = function () {
  4418. return new Size(0.0, 0.0);
  4419. };
  4420. /**
  4421. * Returns a new Size set as the addition result of the current Size and the given one.
  4422. */
  4423. Size.prototype.add = function (otherSize) {
  4424. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4425. return r;
  4426. };
  4427. /**
  4428. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4429. */
  4430. Size.prototype.subtract = function (otherSize) {
  4431. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4432. return r;
  4433. };
  4434. /**
  4435. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4436. */
  4437. Size.Lerp = function (start, end, amount) {
  4438. var w = start.width + ((end.width - start.width) * amount);
  4439. var h = start.height + ((end.height - start.height) * amount);
  4440. return new Size(w, h);
  4441. };
  4442. return Size;
  4443. }());
  4444. BABYLON.Size = Size;
  4445. /**
  4446. * Class used to store quaternion data
  4447. * @see https://en.wikipedia.org/wiki/Quaternion
  4448. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4449. */
  4450. var Quaternion = /** @class */ (function () {
  4451. /**
  4452. * Creates a new Quaternion from the given floats
  4453. * @param x defines the first component (0 by default)
  4454. * @param y defines the second component (0 by default)
  4455. * @param z defines the third component (0 by default)
  4456. * @param w defines the fourth component (1.0 by default)
  4457. */
  4458. function Quaternion(
  4459. /** defines the first component (0 by default) */
  4460. x,
  4461. /** defines the second component (0 by default) */
  4462. y,
  4463. /** defines the third component (0 by default) */
  4464. z,
  4465. /** defines the fourth component (1.0 by default) */
  4466. w) {
  4467. if (x === void 0) { x = 0.0; }
  4468. if (y === void 0) { y = 0.0; }
  4469. if (z === void 0) { z = 0.0; }
  4470. if (w === void 0) { w = 1.0; }
  4471. this.x = x;
  4472. this.y = y;
  4473. this.z = z;
  4474. this.w = w;
  4475. }
  4476. /**
  4477. * Gets a string representation for the current quaternion
  4478. * @returns a string with the Quaternion coordinates
  4479. */
  4480. Quaternion.prototype.toString = function () {
  4481. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4482. };
  4483. /**
  4484. * Gets the class name of the quaternion
  4485. * @returns the string "Quaternion"
  4486. */
  4487. Quaternion.prototype.getClassName = function () {
  4488. return "Quaternion";
  4489. };
  4490. /**
  4491. * Gets a hash code for this quaternion
  4492. * @returns the quaternion hash code
  4493. */
  4494. Quaternion.prototype.getHashCode = function () {
  4495. var hash = this.x || 0;
  4496. hash = (hash * 397) ^ (this.y || 0);
  4497. hash = (hash * 397) ^ (this.z || 0);
  4498. hash = (hash * 397) ^ (this.w || 0);
  4499. return hash;
  4500. };
  4501. /**
  4502. * Copy the quaternion to an array
  4503. * @returns a new array populated with 4 elements from the quaternion coordinates
  4504. */
  4505. Quaternion.prototype.asArray = function () {
  4506. return [this.x, this.y, this.z, this.w];
  4507. };
  4508. /**
  4509. * Check if two quaternions are equals
  4510. * @param otherQuaternion defines the second operand
  4511. * @return true if the current quaternion and the given one coordinates are strictly equals
  4512. */
  4513. Quaternion.prototype.equals = function (otherQuaternion) {
  4514. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4515. };
  4516. /**
  4517. * Clone the current quaternion
  4518. * @returns a new quaternion copied from the current one
  4519. */
  4520. Quaternion.prototype.clone = function () {
  4521. return new Quaternion(this.x, this.y, this.z, this.w);
  4522. };
  4523. /**
  4524. * Copy a quaternion to the current one
  4525. * @param other defines the other quaternion
  4526. * @returns the updated current quaternion
  4527. */
  4528. Quaternion.prototype.copyFrom = function (other) {
  4529. this.x = other.x;
  4530. this.y = other.y;
  4531. this.z = other.z;
  4532. this.w = other.w;
  4533. return this;
  4534. };
  4535. /**
  4536. * Updates the current quaternion with the given float coordinates
  4537. * @param x defines the x coordinate
  4538. * @param y defines the y coordinate
  4539. * @param z defines the z coordinate
  4540. * @param w defines the w coordinate
  4541. * @returns the updated current quaternion
  4542. */
  4543. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4544. this.x = x;
  4545. this.y = y;
  4546. this.z = z;
  4547. this.w = w;
  4548. return this;
  4549. };
  4550. /**
  4551. * Updates the current quaternion from the given float coordinates
  4552. * @param x defines the x coordinate
  4553. * @param y defines the y coordinate
  4554. * @param z defines the z coordinate
  4555. * @param w defines the w coordinate
  4556. * @returns the updated current quaternion
  4557. */
  4558. Quaternion.prototype.set = function (x, y, z, w) {
  4559. return this.copyFromFloats(x, y, z, w);
  4560. };
  4561. /**
  4562. * Adds two quaternions
  4563. * @param other defines the second operand
  4564. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4565. */
  4566. Quaternion.prototype.add = function (other) {
  4567. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4568. };
  4569. /**
  4570. * Add a quaternion to the current one
  4571. * @param other defines the quaternion to add
  4572. * @returns the current quaternion
  4573. */
  4574. Quaternion.prototype.addInPlace = function (other) {
  4575. this.x += other.x;
  4576. this.y += other.y;
  4577. this.z += other.z;
  4578. this.w += other.w;
  4579. return this;
  4580. };
  4581. /**
  4582. * Subtract two quaternions
  4583. * @param other defines the second operand
  4584. * @returns a new quaternion as the subtraction result of the given one from the current one
  4585. */
  4586. Quaternion.prototype.subtract = function (other) {
  4587. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4588. };
  4589. /**
  4590. * Multiplies the current quaternion by a scale factor
  4591. * @param value defines the scale factor
  4592. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4593. */
  4594. Quaternion.prototype.scale = function (value) {
  4595. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4596. };
  4597. /**
  4598. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4599. * @param scale defines the scale factor
  4600. * @param result defines the Quaternion object where to store the result
  4601. * @returns the unmodified current quaternion
  4602. */
  4603. Quaternion.prototype.scaleToRef = function (scale, result) {
  4604. result.x = this.x * scale;
  4605. result.y = this.y * scale;
  4606. result.z = this.z * scale;
  4607. result.w = this.w * scale;
  4608. return this;
  4609. };
  4610. /**
  4611. * Multiplies in place the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns the current modified quaternion
  4614. */
  4615. Quaternion.prototype.scaleInPlace = function (value) {
  4616. this.x *= value;
  4617. this.y *= value;
  4618. this.z *= value;
  4619. this.w *= value;
  4620. return this;
  4621. };
  4622. /**
  4623. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4624. * @param scale defines the scale factor
  4625. * @param result defines the Quaternion object where to store the result
  4626. * @returns the unmodified current quaternion
  4627. */
  4628. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4629. result.x += this.x * scale;
  4630. result.y += this.y * scale;
  4631. result.z += this.z * scale;
  4632. result.w += this.w * scale;
  4633. return this;
  4634. };
  4635. /**
  4636. * Multiplies two quaternions
  4637. * @param q1 defines the second operand
  4638. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4639. */
  4640. Quaternion.prototype.multiply = function (q1) {
  4641. var result = new Quaternion(0, 0, 0, 1.0);
  4642. this.multiplyToRef(q1, result);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4647. * @param q1 defines the second operand
  4648. * @param result defines the target quaternion
  4649. * @returns the current quaternion
  4650. */
  4651. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4652. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4653. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4654. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4655. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4656. result.copyFromFloats(x, y, z, w);
  4657. return this;
  4658. };
  4659. /**
  4660. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @returns the currentupdated quaternion
  4663. */
  4664. Quaternion.prototype.multiplyInPlace = function (q1) {
  4665. this.multiplyToRef(q1, this);
  4666. return this;
  4667. };
  4668. /**
  4669. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4670. * @param ref defines the target quaternion
  4671. * @returns the current quaternion
  4672. */
  4673. Quaternion.prototype.conjugateToRef = function (ref) {
  4674. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates in place (1-q) the current quaternion
  4679. * @returns the current updated quaternion
  4680. */
  4681. Quaternion.prototype.conjugateInPlace = function () {
  4682. this.x *= -1;
  4683. this.y *= -1;
  4684. this.z *= -1;
  4685. return this;
  4686. };
  4687. /**
  4688. * Conjugates in place (1-q) the current quaternion
  4689. * @returns a new quaternion
  4690. */
  4691. Quaternion.prototype.conjugate = function () {
  4692. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4693. return result;
  4694. };
  4695. /**
  4696. * Gets length of current quaternion
  4697. * @returns the quaternion length (float)
  4698. */
  4699. Quaternion.prototype.length = function () {
  4700. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4701. };
  4702. /**
  4703. * Normalize in place the current quaternion
  4704. * @returns the current updated quaternion
  4705. */
  4706. Quaternion.prototype.normalize = function () {
  4707. var length = 1.0 / this.length();
  4708. this.x *= length;
  4709. this.y *= length;
  4710. this.z *= length;
  4711. this.w *= length;
  4712. return this;
  4713. };
  4714. /**
  4715. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4716. * @param order is a reserved parameter and is ignore for now
  4717. * @returns a new Vector3 containing the Euler angles
  4718. */
  4719. Quaternion.prototype.toEulerAngles = function (order) {
  4720. if (order === void 0) { order = "YZX"; }
  4721. var result = Vector3.Zero();
  4722. this.toEulerAnglesToRef(result, order);
  4723. return result;
  4724. };
  4725. /**
  4726. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4727. * @param result defines the vector which will be filled with the Euler angles
  4728. * @param order is a reserved parameter and is ignore for now
  4729. * @returns the current unchanged quaternion
  4730. */
  4731. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4732. if (order === void 0) { order = "YZX"; }
  4733. var qz = this.z;
  4734. var qx = this.x;
  4735. var qy = this.y;
  4736. var qw = this.w;
  4737. var sqw = qw * qw;
  4738. var sqz = qz * qz;
  4739. var sqx = qx * qx;
  4740. var sqy = qy * qy;
  4741. var zAxisY = qy * qz - qx * qw;
  4742. var limit = .4999999;
  4743. if (zAxisY < -limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else if (zAxisY > limit) {
  4749. result.y = 2 * Math.atan2(qy, qw);
  4750. result.x = -Math.PI / 2;
  4751. result.z = 0;
  4752. }
  4753. else {
  4754. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4755. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4756. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4757. }
  4758. return this;
  4759. };
  4760. /**
  4761. * Updates the given rotation matrix with the current quaternion values
  4762. * @param result defines the target matrix
  4763. * @returns the current unchanged quaternion
  4764. */
  4765. Quaternion.prototype.toRotationMatrix = function (result) {
  4766. var xx = this.x * this.x;
  4767. var yy = this.y * this.y;
  4768. var zz = this.z * this.z;
  4769. var xy = this.x * this.y;
  4770. var zw = this.z * this.w;
  4771. var zx = this.z * this.x;
  4772. var yw = this.y * this.w;
  4773. var yz = this.y * this.z;
  4774. var xw = this.x * this.w;
  4775. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4776. result.m[1] = 2.0 * (xy + zw);
  4777. result.m[2] = 2.0 * (zx - yw);
  4778. result.m[3] = 0;
  4779. result.m[4] = 2.0 * (xy - zw);
  4780. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4781. result.m[6] = 2.0 * (yz + xw);
  4782. result.m[7] = 0;
  4783. result.m[8] = 2.0 * (zx + yw);
  4784. result.m[9] = 2.0 * (yz - xw);
  4785. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4786. result.m[11] = 0;
  4787. result.m[12] = 0;
  4788. result.m[13] = 0;
  4789. result.m[14] = 0;
  4790. result.m[15] = 1.0;
  4791. result._markAsUpdated();
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion from the given rotation matrix values
  4796. * @param matrix defines the source matrix
  4797. * @returns the current updated quaternion
  4798. */
  4799. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4800. Quaternion.FromRotationMatrixToRef(matrix, this);
  4801. return this;
  4802. };
  4803. // Statics
  4804. /**
  4805. * Creates a new quaternion from a rotation matrix
  4806. * @param matrix defines the source matrix
  4807. * @returns a new quaternion created from the given rotation matrix values
  4808. */
  4809. Quaternion.FromRotationMatrix = function (matrix) {
  4810. var result = new Quaternion();
  4811. Quaternion.FromRotationMatrixToRef(matrix, result);
  4812. return result;
  4813. };
  4814. /**
  4815. * Updates the given quaternion with the given rotation matrix values
  4816. * @param matrix defines the source matrix
  4817. * @param result defines the target quaternion
  4818. */
  4819. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4820. var data = matrix.m;
  4821. var m11 = data[0], m12 = data[4], m13 = data[8];
  4822. var m21 = data[1], m22 = data[5], m23 = data[9];
  4823. var m31 = data[2], m32 = data[6], m33 = data[10];
  4824. var trace = m11 + m22 + m33;
  4825. var s;
  4826. if (trace > 0) {
  4827. s = 0.5 / Math.sqrt(trace + 1.0);
  4828. result.w = 0.25 / s;
  4829. result.x = (m32 - m23) * s;
  4830. result.y = (m13 - m31) * s;
  4831. result.z = (m21 - m12) * s;
  4832. }
  4833. else if (m11 > m22 && m11 > m33) {
  4834. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4835. result.w = (m32 - m23) / s;
  4836. result.x = 0.25 * s;
  4837. result.y = (m12 + m21) / s;
  4838. result.z = (m13 + m31) / s;
  4839. }
  4840. else if (m22 > m33) {
  4841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4842. result.w = (m13 - m31) / s;
  4843. result.x = (m12 + m21) / s;
  4844. result.y = 0.25 * s;
  4845. result.z = (m23 + m32) / s;
  4846. }
  4847. else {
  4848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4849. result.w = (m21 - m12) / s;
  4850. result.x = (m13 + m31) / s;
  4851. result.y = (m23 + m32) / s;
  4852. result.z = 0.25 * s;
  4853. }
  4854. };
  4855. /**
  4856. * Returns the dot product (float) between the quaternions "left" and "right"
  4857. * @param left defines the left operand
  4858. * @param right defines the right operand
  4859. * @returns the dot product
  4860. */
  4861. Quaternion.Dot = function (left, right) {
  4862. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4863. };
  4864. /**
  4865. * Checks if the two quaternions are close to each other
  4866. * @param quat0 defines the first quaternion to check
  4867. * @param quat1 defines the second quaternion to check
  4868. * @returns true if the two quaternions are close to each other
  4869. */
  4870. Quaternion.AreClose = function (quat0, quat1) {
  4871. var dot = Quaternion.Dot(quat0, quat1);
  4872. return dot >= 0;
  4873. };
  4874. /**
  4875. * Creates an empty quaternion
  4876. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4877. */
  4878. Quaternion.Zero = function () {
  4879. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4880. };
  4881. /**
  4882. * Inverse a given quaternion
  4883. * @param q defines the source quaternion
  4884. * @returns a new quaternion as the inverted current quaternion
  4885. */
  4886. Quaternion.Inverse = function (q) {
  4887. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4888. };
  4889. /**
  4890. * Creates an identity quaternion
  4891. * @returns the identity quaternion
  4892. */
  4893. Quaternion.Identity = function () {
  4894. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4895. };
  4896. /**
  4897. * Gets a boolean indicating if the given quaternion is identity
  4898. * @param quaternion defines the quaternion to check
  4899. * @returns true if the quaternion is identity
  4900. */
  4901. Quaternion.IsIdentity = function (quaternion) {
  4902. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4903. };
  4904. /**
  4905. * Creates a quaternion from a rotation around an axis
  4906. * @param axis defines the axis to use
  4907. * @param angle defines the angle to use
  4908. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4909. */
  4910. Quaternion.RotationAxis = function (axis, angle) {
  4911. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4912. };
  4913. /**
  4914. * Creates a rotation around an axis and stores it into the given quaternion
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @param result defines the target quaternion
  4918. * @returns the target quaternion
  4919. */
  4920. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4921. var sin = Math.sin(angle / 2);
  4922. axis.normalize();
  4923. result.w = Math.cos(angle / 2);
  4924. result.x = axis.x * sin;
  4925. result.y = axis.y * sin;
  4926. result.z = axis.z * sin;
  4927. return result;
  4928. };
  4929. /**
  4930. * Creates a new quaternion from data stored into an array
  4931. * @param array defines the data source
  4932. * @param offset defines the offset in the source array where the data starts
  4933. * @returns a new quaternion
  4934. */
  4935. Quaternion.FromArray = function (array, offset) {
  4936. if (!offset) {
  4937. offset = 0;
  4938. }
  4939. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4940. };
  4941. /**
  4942. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4943. * @param yaw defines the rotation around Y axis
  4944. * @param pitch defines the rotation around X axis
  4945. * @param roll defines the rotation around Z axis
  4946. * @returns the new quaternion
  4947. */
  4948. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4949. var q = new Quaternion();
  4950. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4951. return q;
  4952. };
  4953. /**
  4954. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4955. * @param yaw defines the rotation around Y axis
  4956. * @param pitch defines the rotation around X axis
  4957. * @param roll defines the rotation around Z axis
  4958. * @param result defines the target quaternion
  4959. */
  4960. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4961. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4962. var halfRoll = roll * 0.5;
  4963. var halfPitch = pitch * 0.5;
  4964. var halfYaw = yaw * 0.5;
  4965. var sinRoll = Math.sin(halfRoll);
  4966. var cosRoll = Math.cos(halfRoll);
  4967. var sinPitch = Math.sin(halfPitch);
  4968. var cosPitch = Math.cos(halfPitch);
  4969. var sinYaw = Math.sin(halfYaw);
  4970. var cosYaw = Math.cos(halfYaw);
  4971. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4972. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4973. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4974. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4975. };
  4976. /**
  4977. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4978. * @param alpha defines the rotation around first axis
  4979. * @param beta defines the rotation around second axis
  4980. * @param gamma defines the rotation around third axis
  4981. * @returns the new quaternion
  4982. */
  4983. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4984. var result = new Quaternion();
  4985. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4986. return result;
  4987. };
  4988. /**
  4989. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4990. * @param alpha defines the rotation around first axis
  4991. * @param beta defines the rotation around second axis
  4992. * @param gamma defines the rotation around third axis
  4993. * @param result defines the target quaternion
  4994. */
  4995. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4996. // Produces a quaternion from Euler angles in the z-x-z orientation
  4997. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4998. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4999. var halfBeta = beta * 0.5;
  5000. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5001. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5002. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5003. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5004. };
  5005. /**
  5006. * 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)
  5007. * @param axis1 defines the first axis
  5008. * @param axis2 defines the second axis
  5009. * @param axis3 defines the third axis
  5010. * @returns the new quaternion
  5011. */
  5012. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5013. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5014. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5015. return quat;
  5016. };
  5017. /**
  5018. * 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
  5019. * @param axis1 defines the first axis
  5020. * @param axis2 defines the second axis
  5021. * @param axis3 defines the third axis
  5022. * @param ref defines the target quaternion
  5023. */
  5024. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5025. var rotMat = MathTmp.Matrix[0];
  5026. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5027. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5028. };
  5029. /**
  5030. * Interpolates between two quaternions
  5031. * @param left defines first quaternion
  5032. * @param right defines second quaternion
  5033. * @param amount defines the gradient to use
  5034. * @returns the new interpolated quaternion
  5035. */
  5036. Quaternion.Slerp = function (left, right, amount) {
  5037. var result = Quaternion.Identity();
  5038. Quaternion.SlerpToRef(left, right, amount, result);
  5039. return result;
  5040. };
  5041. /**
  5042. * Interpolates between two quaternions and stores it into a target quaternion
  5043. * @param left defines first quaternion
  5044. * @param right defines second quaternion
  5045. * @param amount defines the gradient to use
  5046. * @param result defines the target quaternion
  5047. */
  5048. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5049. var num2;
  5050. var num3;
  5051. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5052. var flag = false;
  5053. if (num4 < 0) {
  5054. flag = true;
  5055. num4 = -num4;
  5056. }
  5057. if (num4 > 0.999999) {
  5058. num3 = 1 - amount;
  5059. num2 = flag ? -amount : amount;
  5060. }
  5061. else {
  5062. var num5 = Math.acos(num4);
  5063. var num6 = (1.0 / Math.sin(num5));
  5064. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5065. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5066. }
  5067. result.x = (num3 * left.x) + (num2 * right.x);
  5068. result.y = (num3 * left.y) + (num2 * right.y);
  5069. result.z = (num3 * left.z) + (num2 * right.z);
  5070. result.w = (num3 * left.w) + (num2 * right.w);
  5071. };
  5072. /**
  5073. * Interpolate between two quaternions using Hermite interpolation
  5074. * @param value1 defines first quaternion
  5075. * @param tangent1 defines the incoming tangent
  5076. * @param value2 defines second quaternion
  5077. * @param tangent2 defines the outgoing tangent
  5078. * @param amount defines the target quaternion
  5079. * @returns the new interpolated quaternion
  5080. */
  5081. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5082. var squared = amount * amount;
  5083. var cubed = amount * squared;
  5084. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5085. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5086. var part3 = (cubed - (2.0 * squared)) + amount;
  5087. var part4 = cubed - squared;
  5088. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5089. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5090. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5091. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5092. return new Quaternion(x, y, z, w);
  5093. };
  5094. return Quaternion;
  5095. }());
  5096. BABYLON.Quaternion = Quaternion;
  5097. /**
  5098. * Class used to store matrix data (4x4)
  5099. */
  5100. var Matrix = /** @class */ (function () {
  5101. /**
  5102. * Creates an empty matrix (filled with zeros)
  5103. */
  5104. function Matrix() {
  5105. this._isIdentity = false;
  5106. this._isIdentityDirty = true;
  5107. /**
  5108. * Gets or sets the internal data of the matrix
  5109. */
  5110. this.m = new Float32Array(16);
  5111. this._markAsUpdated();
  5112. }
  5113. /** @hidden */
  5114. Matrix.prototype._markAsUpdated = function () {
  5115. this.updateFlag = Matrix._updateFlagSeed++;
  5116. this._isIdentityDirty = true;
  5117. };
  5118. // Properties
  5119. /**
  5120. * Check if the current matrix is indentity
  5121. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5122. * @returns true is the matrix is the identity matrix
  5123. */
  5124. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5125. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5126. if (this._isIdentityDirty) {
  5127. this._isIdentityDirty = false;
  5128. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5132. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5133. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5134. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. else {
  5138. this._isIdentity = true;
  5139. }
  5140. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5141. this._isIdentity = false;
  5142. }
  5143. }
  5144. return this._isIdentity;
  5145. };
  5146. /**
  5147. * Gets the determinant of the matrix
  5148. * @returns the matrix determinant
  5149. */
  5150. Matrix.prototype.determinant = function () {
  5151. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5152. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5153. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5154. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5155. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5156. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5157. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5158. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5159. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5160. };
  5161. // Methods
  5162. /**
  5163. * Returns the matrix as a Float32Array
  5164. * @returns the matrix underlying array
  5165. */
  5166. Matrix.prototype.toArray = function () {
  5167. return this.m;
  5168. };
  5169. /**
  5170. * Returns the matrix as a Float32Array
  5171. * @returns the matrix underlying array.
  5172. */
  5173. Matrix.prototype.asArray = function () {
  5174. return this.toArray();
  5175. };
  5176. /**
  5177. * Inverts the current matrix in place
  5178. * @returns the current inverted matrix
  5179. */
  5180. Matrix.prototype.invert = function () {
  5181. this.invertToRef(this);
  5182. return this;
  5183. };
  5184. /**
  5185. * Sets all the matrix elements to zero
  5186. * @returns the current matrix
  5187. */
  5188. Matrix.prototype.reset = function () {
  5189. for (var index = 0; index < 16; index++) {
  5190. this.m[index] = 0.0;
  5191. }
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Adds the current matrix with a second one
  5197. * @param other defines the matrix to add
  5198. * @returns a new matrix as the addition of the current matrix and the given one
  5199. */
  5200. Matrix.prototype.add = function (other) {
  5201. var result = new Matrix();
  5202. this.addToRef(other, result);
  5203. return result;
  5204. };
  5205. /**
  5206. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5207. * @param other defines the matrix to add
  5208. * @param result defines the target matrix
  5209. * @returns the current matrix
  5210. */
  5211. Matrix.prototype.addToRef = function (other, result) {
  5212. for (var index = 0; index < 16; index++) {
  5213. result.m[index] = this.m[index] + other.m[index];
  5214. }
  5215. result._markAsUpdated();
  5216. return this;
  5217. };
  5218. /**
  5219. * Adds in place the given matrix to the current matrix
  5220. * @param other defines the second operand
  5221. * @returns the current updated matrix
  5222. */
  5223. Matrix.prototype.addToSelf = function (other) {
  5224. for (var index = 0; index < 16; index++) {
  5225. this.m[index] += other.m[index];
  5226. }
  5227. this._markAsUpdated();
  5228. return this;
  5229. };
  5230. /**
  5231. * Sets the given matrix to the current inverted Matrix
  5232. * @param other defines the target matrix
  5233. * @returns the unmodified current matrix
  5234. */
  5235. Matrix.prototype.invertToRef = function (other) {
  5236. var l1 = this.m[0];
  5237. var l2 = this.m[1];
  5238. var l3 = this.m[2];
  5239. var l4 = this.m[3];
  5240. var l5 = this.m[4];
  5241. var l6 = this.m[5];
  5242. var l7 = this.m[6];
  5243. var l8 = this.m[7];
  5244. var l9 = this.m[8];
  5245. var l10 = this.m[9];
  5246. var l11 = this.m[10];
  5247. var l12 = this.m[11];
  5248. var l13 = this.m[12];
  5249. var l14 = this.m[13];
  5250. var l15 = this.m[14];
  5251. var l16 = this.m[15];
  5252. var l17 = (l11 * l16) - (l12 * l15);
  5253. var l18 = (l10 * l16) - (l12 * l14);
  5254. var l19 = (l10 * l15) - (l11 * l14);
  5255. var l20 = (l9 * l16) - (l12 * l13);
  5256. var l21 = (l9 * l15) - (l11 * l13);
  5257. var l22 = (l9 * l14) - (l10 * l13);
  5258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5263. var l28 = (l7 * l16) - (l8 * l15);
  5264. var l29 = (l6 * l16) - (l8 * l14);
  5265. var l30 = (l6 * l15) - (l7 * l14);
  5266. var l31 = (l5 * l16) - (l8 * l13);
  5267. var l32 = (l5 * l15) - (l7 * l13);
  5268. var l33 = (l5 * l14) - (l6 * l13);
  5269. var l34 = (l7 * l12) - (l8 * l11);
  5270. var l35 = (l6 * l12) - (l8 * l10);
  5271. var l36 = (l6 * l11) - (l7 * l10);
  5272. var l37 = (l5 * l12) - (l8 * l9);
  5273. var l38 = (l5 * l11) - (l7 * l9);
  5274. var l39 = (l5 * l10) - (l6 * l9);
  5275. other.m[0] = l23 * l27;
  5276. other.m[4] = l24 * l27;
  5277. other.m[8] = l25 * l27;
  5278. other.m[12] = l26 * l27;
  5279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5291. other._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Inserts the translation vector (using 3 floats) in the current matrix
  5296. * @param x defines the 1st component of the translation
  5297. * @param y defines the 2nd component of the translation
  5298. * @param z defines the 3rd component of the translation
  5299. * @returns the current updated matrix
  5300. */
  5301. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5302. this.m[12] = x;
  5303. this.m[13] = y;
  5304. this.m[14] = z;
  5305. this._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector in the current matrix
  5310. * @param vector3 defines the translation to insert
  5311. * @returns the current updated matrix
  5312. */
  5313. Matrix.prototype.setTranslation = function (vector3) {
  5314. this.m[12] = vector3.x;
  5315. this.m[13] = vector3.y;
  5316. this.m[14] = vector3.z;
  5317. this._markAsUpdated();
  5318. return this;
  5319. };
  5320. /**
  5321. * Gets the translation value of the current matrix
  5322. * @returns a new Vector3 as the extracted translation from the matrix
  5323. */
  5324. Matrix.prototype.getTranslation = function () {
  5325. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5326. };
  5327. /**
  5328. * Fill a Vector3 with the extracted translation from the matrix
  5329. * @param result defines the Vector3 where to store the translation
  5330. * @returns the current matrix
  5331. */
  5332. Matrix.prototype.getTranslationToRef = function (result) {
  5333. result.x = this.m[12];
  5334. result.y = this.m[13];
  5335. result.z = this.m[14];
  5336. return this;
  5337. };
  5338. /**
  5339. * Remove rotation and scaling part from the matrix
  5340. * @returns the updated matrix
  5341. */
  5342. Matrix.prototype.removeRotationAndScaling = function () {
  5343. this.setRowFromFloats(0, 1, 0, 0, 0);
  5344. this.setRowFromFloats(1, 0, 1, 0, 0);
  5345. this.setRowFromFloats(2, 0, 0, 1, 0);
  5346. return this;
  5347. };
  5348. /**
  5349. * Multiply two matrices
  5350. * @param other defines the second operand
  5351. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5352. */
  5353. Matrix.prototype.multiply = function (other) {
  5354. var result = new Matrix();
  5355. this.multiplyToRef(other, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Copy the current matrix from the given one
  5360. * @param other defines the source matrix
  5361. * @returns the current updated matrix
  5362. */
  5363. Matrix.prototype.copyFrom = function (other) {
  5364. for (var index = 0; index < 16; index++) {
  5365. this.m[index] = other.m[index];
  5366. }
  5367. this._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Populates the given array from the starting index with the current matrix values
  5372. * @param array defines the target array
  5373. * @param offset defines the offset in the target array where to start storing values
  5374. * @returns the current matrix
  5375. */
  5376. Matrix.prototype.copyToArray = function (array, offset) {
  5377. if (offset === void 0) { offset = 0; }
  5378. for (var index = 0; index < 16; index++) {
  5379. array[offset + index] = this.m[index];
  5380. }
  5381. return this;
  5382. };
  5383. /**
  5384. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5385. * @param other defines the second operand
  5386. * @param result defines the matrix where to store the multiplication
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.multiplyToRef = function (other, result) {
  5390. this.multiplyToArray(other, result.m, 0);
  5391. result._markAsUpdated();
  5392. return this;
  5393. };
  5394. /**
  5395. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5396. * @param other defines the second operand
  5397. * @param result defines the array where to store the multiplication
  5398. * @param offset defines the offset in the target array where to start storing values
  5399. * @returns the current matrix
  5400. */
  5401. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5402. var tm0 = this.m[0];
  5403. var tm1 = this.m[1];
  5404. var tm2 = this.m[2];
  5405. var tm3 = this.m[3];
  5406. var tm4 = this.m[4];
  5407. var tm5 = this.m[5];
  5408. var tm6 = this.m[6];
  5409. var tm7 = this.m[7];
  5410. var tm8 = this.m[8];
  5411. var tm9 = this.m[9];
  5412. var tm10 = this.m[10];
  5413. var tm11 = this.m[11];
  5414. var tm12 = this.m[12];
  5415. var tm13 = this.m[13];
  5416. var tm14 = this.m[14];
  5417. var tm15 = this.m[15];
  5418. var om0 = other.m[0];
  5419. var om1 = other.m[1];
  5420. var om2 = other.m[2];
  5421. var om3 = other.m[3];
  5422. var om4 = other.m[4];
  5423. var om5 = other.m[5];
  5424. var om6 = other.m[6];
  5425. var om7 = other.m[7];
  5426. var om8 = other.m[8];
  5427. var om9 = other.m[9];
  5428. var om10 = other.m[10];
  5429. var om11 = other.m[11];
  5430. var om12 = other.m[12];
  5431. var om13 = other.m[13];
  5432. var om14 = other.m[14];
  5433. var om15 = other.m[15];
  5434. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5435. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5436. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5437. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5438. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5439. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5440. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5441. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5442. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5443. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5444. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5445. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5446. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5447. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5448. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5449. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5450. return this;
  5451. };
  5452. /**
  5453. * Check equality between this matrix and a second one
  5454. * @param value defines the second matrix to compare
  5455. * @returns true is the current matrix and the given one values are strictly equal
  5456. */
  5457. Matrix.prototype.equals = function (value) {
  5458. return value &&
  5459. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5460. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5461. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5462. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5463. };
  5464. /**
  5465. * Clone the current matrix
  5466. * @returns a new matrix from the current matrix
  5467. */
  5468. Matrix.prototype.clone = function () {
  5469. 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]);
  5470. };
  5471. /**
  5472. * Returns the name of the current matrix class
  5473. * @returns the string "Matrix"
  5474. */
  5475. Matrix.prototype.getClassName = function () {
  5476. return "Matrix";
  5477. };
  5478. /**
  5479. * Gets the hash code of the current matrix
  5480. * @returns the hash code
  5481. */
  5482. Matrix.prototype.getHashCode = function () {
  5483. var hash = this.m[0] || 0;
  5484. for (var i = 1; i < 16; i++) {
  5485. hash = (hash * 397) ^ (this.m[i] || 0);
  5486. }
  5487. return hash;
  5488. };
  5489. /**
  5490. * Decomposes the current Matrix into a translation, rotation and scaling components
  5491. * @param scale defines the scale vector3 given as a reference to update
  5492. * @param rotation defines the rotation quaternion given as a reference to update
  5493. * @param translation defines the translation vector3 given as a reference to update
  5494. * @returns true if operation was successful
  5495. */
  5496. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5497. if (translation) {
  5498. translation.x = this.m[12];
  5499. translation.y = this.m[13];
  5500. translation.z = this.m[14];
  5501. }
  5502. scale = scale || MathTmp.Vector3[0];
  5503. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5504. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5505. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5506. if (this.determinant() <= 0) {
  5507. scale.y *= -1;
  5508. }
  5509. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5510. if (rotation) {
  5511. rotation.x = 0;
  5512. rotation.y = 0;
  5513. rotation.z = 0;
  5514. rotation.w = 1;
  5515. }
  5516. return false;
  5517. }
  5518. if (rotation) {
  5519. 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]);
  5520. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5521. }
  5522. return true;
  5523. };
  5524. /**
  5525. * Gets specific row of the matrix
  5526. * @param index defines the number of the row to get
  5527. * @returns the index-th row of the current matrix as a new Vector4
  5528. */
  5529. Matrix.prototype.getRow = function (index) {
  5530. if (index < 0 || index > 3) {
  5531. return null;
  5532. }
  5533. var i = index * 4;
  5534. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5535. };
  5536. /**
  5537. * Sets the index-th row of the current matrix to the vector4 values
  5538. * @param index defines the number of the row to set
  5539. * @param row defines the target vector4
  5540. * @returns the updated current matrix
  5541. */
  5542. Matrix.prototype.setRow = function (index, row) {
  5543. if (index < 0 || index > 3) {
  5544. return this;
  5545. }
  5546. var i = index * 4;
  5547. this.m[i + 0] = row.x;
  5548. this.m[i + 1] = row.y;
  5549. this.m[i + 2] = row.z;
  5550. this.m[i + 3] = row.w;
  5551. this._markAsUpdated();
  5552. return this;
  5553. };
  5554. /**
  5555. * Compute the transpose of the matrix
  5556. * @returns the new transposed matrix
  5557. */
  5558. Matrix.prototype.transpose = function () {
  5559. return Matrix.Transpose(this);
  5560. };
  5561. /**
  5562. * Compute the transpose of the matrix and store it in a given matrix
  5563. * @param result defines the target matrix
  5564. * @returns the current matrix
  5565. */
  5566. Matrix.prototype.transposeToRef = function (result) {
  5567. Matrix.TransposeToRef(this, result);
  5568. return this;
  5569. };
  5570. /**
  5571. * Sets the index-th row of the current matrix with the given 4 x float values
  5572. * @param index defines the row index
  5573. * @param x defines the x component to set
  5574. * @param y defines the y component to set
  5575. * @param z defines the z component to set
  5576. * @param w defines the w component to set
  5577. * @returns the updated current matrix
  5578. */
  5579. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5580. if (index < 0 || index > 3) {
  5581. return this;
  5582. }
  5583. var i = index * 4;
  5584. this.m[i + 0] = x;
  5585. this.m[i + 1] = y;
  5586. this.m[i + 2] = z;
  5587. this.m[i + 3] = w;
  5588. this._markAsUpdated();
  5589. return this;
  5590. };
  5591. /**
  5592. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5593. * @param scale defines the scale factor
  5594. * @returns a new matrix
  5595. */
  5596. Matrix.prototype.scale = function (scale) {
  5597. var result = new Matrix();
  5598. this.scaleToRef(scale, result);
  5599. return result;
  5600. };
  5601. /**
  5602. * Scale the current matrix values by a factor to a given result matrix
  5603. * @param scale defines the scale factor
  5604. * @param result defines the matrix to store the result
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.scaleToRef = function (scale, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] = this.m[index] * scale;
  5610. }
  5611. result._markAsUpdated();
  5612. return this;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor and add the result to a given matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the Matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] += this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5629. * @param ref matrix to store the result
  5630. */
  5631. Matrix.prototype.toNormalMatrix = function (ref) {
  5632. this.invertToRef(ref);
  5633. ref.transpose();
  5634. var m = ref.m;
  5635. 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);
  5636. };
  5637. /**
  5638. * Gets only rotation part of the current matrix
  5639. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5640. */
  5641. Matrix.prototype.getRotationMatrix = function () {
  5642. var result = Matrix.Identity();
  5643. this.getRotationMatrixToRef(result);
  5644. return result;
  5645. };
  5646. /**
  5647. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5648. * @param result defines the target matrix to store data to
  5649. * @returns the current matrix
  5650. */
  5651. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5652. var m = this.m;
  5653. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5654. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5655. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5656. if (this.determinant() <= 0) {
  5657. sy *= -1;
  5658. }
  5659. if (sx === 0 || sy === 0 || sz === 0) {
  5660. Matrix.IdentityToRef(result);
  5661. }
  5662. else {
  5663. 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);
  5664. }
  5665. return this;
  5666. };
  5667. // Statics
  5668. /**
  5669. * Creates a matrix from an array
  5670. * @param array defines the source array
  5671. * @param offset defines an offset in the source array
  5672. * @returns a new Matrix set from the starting index of the given array
  5673. */
  5674. Matrix.FromArray = function (array, offset) {
  5675. var result = new Matrix();
  5676. if (!offset) {
  5677. offset = 0;
  5678. }
  5679. Matrix.FromArrayToRef(array, offset, result);
  5680. return result;
  5681. };
  5682. /**
  5683. * Copy the content of an array into a given matrix
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @param result defines the target matrix
  5687. */
  5688. Matrix.FromArrayToRef = function (array, offset, result) {
  5689. for (var index = 0; index < 16; index++) {
  5690. result.m[index] = array[index + offset];
  5691. }
  5692. result._markAsUpdated();
  5693. };
  5694. /**
  5695. * Stores an array into a matrix after having multiplied each component by a given factor
  5696. * @param array defines the source array
  5697. * @param offset defines the offset in the source array
  5698. * @param scale defines the scaling factor
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset] * scale;
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores a list of values (16) inside a given matrix
  5709. * @param initialM11 defines 1st value of 1st row
  5710. * @param initialM12 defines 2nd value of 1st row
  5711. * @param initialM13 defines 3rd value of 1st row
  5712. * @param initialM14 defines 4th value of 1st row
  5713. * @param initialM21 defines 1st value of 2nd row
  5714. * @param initialM22 defines 2nd value of 2nd row
  5715. * @param initialM23 defines 3rd value of 2nd row
  5716. * @param initialM24 defines 4th value of 2nd row
  5717. * @param initialM31 defines 1st value of 3rd row
  5718. * @param initialM32 defines 2nd value of 3rd row
  5719. * @param initialM33 defines 3rd value of 3rd row
  5720. * @param initialM34 defines 4th value of 3rd row
  5721. * @param initialM41 defines 1st value of 4th row
  5722. * @param initialM42 defines 2nd value of 4th row
  5723. * @param initialM43 defines 3rd value of 4th row
  5724. * @param initialM44 defines 4th value of 4th row
  5725. * @param result defines the target matrix
  5726. */
  5727. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5728. result.m[0] = initialM11;
  5729. result.m[1] = initialM12;
  5730. result.m[2] = initialM13;
  5731. result.m[3] = initialM14;
  5732. result.m[4] = initialM21;
  5733. result.m[5] = initialM22;
  5734. result.m[6] = initialM23;
  5735. result.m[7] = initialM24;
  5736. result.m[8] = initialM31;
  5737. result.m[9] = initialM32;
  5738. result.m[10] = initialM33;
  5739. result.m[11] = initialM34;
  5740. result.m[12] = initialM41;
  5741. result.m[13] = initialM42;
  5742. result.m[14] = initialM43;
  5743. result.m[15] = initialM44;
  5744. result._markAsUpdated();
  5745. };
  5746. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5747. /**
  5748. * Gets an identity matrix that must not be updated
  5749. */
  5750. get: function () {
  5751. return Matrix._identityReadOnly;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. /**
  5757. * Creates new matrix from a list of values (16)
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @returns the new matrix
  5775. */
  5776. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5777. var result = new Matrix();
  5778. result.m[0] = initialM11;
  5779. result.m[1] = initialM12;
  5780. result.m[2] = initialM13;
  5781. result.m[3] = initialM14;
  5782. result.m[4] = initialM21;
  5783. result.m[5] = initialM22;
  5784. result.m[6] = initialM23;
  5785. result.m[7] = initialM24;
  5786. result.m[8] = initialM31;
  5787. result.m[9] = initialM32;
  5788. result.m[10] = initialM33;
  5789. result.m[11] = initialM34;
  5790. result.m[12] = initialM41;
  5791. result.m[13] = initialM42;
  5792. result.m[14] = initialM43;
  5793. result.m[15] = initialM44;
  5794. return result;
  5795. };
  5796. /**
  5797. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5798. * @param scale defines the scale vector3
  5799. * @param rotation defines the rotation quaternion
  5800. * @param translation defines the translation vector3
  5801. * @returns a new matrix
  5802. */
  5803. Matrix.Compose = function (scale, rotation, translation) {
  5804. var result = Matrix.Identity();
  5805. Matrix.ComposeToRef(scale, rotation, translation, result);
  5806. return result;
  5807. };
  5808. /**
  5809. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5810. * @param scale defines the scale vector3
  5811. * @param rotation defines the rotation quaternion
  5812. * @param translation defines the translation vector3
  5813. * @param result defines the target matrix
  5814. */
  5815. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5816. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5817. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5818. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5819. result.setTranslation(translation);
  5820. };
  5821. /**
  5822. * Creates a new identity matrix
  5823. * @returns a new identity matrix
  5824. */
  5825. Matrix.Identity = function () {
  5826. 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);
  5827. };
  5828. /**
  5829. * Creates a new identity matrix and stores the result in a given matrix
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.IdentityToRef = function (result) {
  5833. 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);
  5834. };
  5835. /**
  5836. * Creates a new zero matrix
  5837. * @returns a new zero matrix
  5838. */
  5839. Matrix.Zero = function () {
  5840. 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);
  5841. };
  5842. /**
  5843. * Creates a new rotation matrix for "angle" radians around the X axis
  5844. * @param angle defines the angle (in radians) to use
  5845. * @return the new matrix
  5846. */
  5847. Matrix.RotationX = function (angle) {
  5848. var result = new Matrix();
  5849. Matrix.RotationXToRef(angle, result);
  5850. return result;
  5851. };
  5852. /**
  5853. * Creates a new matrix as the invert of a given matrix
  5854. * @param source defines the source matrix
  5855. * @returns the new matrix
  5856. */
  5857. Matrix.Invert = function (source) {
  5858. var result = new Matrix();
  5859. source.invertToRef(result);
  5860. return result;
  5861. };
  5862. /**
  5863. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5864. * @param angle defines the angle (in radians) to use
  5865. * @param result defines the target matrix
  5866. */
  5867. Matrix.RotationXToRef = function (angle, result) {
  5868. var s = Math.sin(angle);
  5869. var c = Math.cos(angle);
  5870. result.m[0] = 1.0;
  5871. result.m[15] = 1.0;
  5872. result.m[5] = c;
  5873. result.m[10] = c;
  5874. result.m[9] = -s;
  5875. result.m[6] = s;
  5876. result.m[1] = 0.0;
  5877. result.m[2] = 0.0;
  5878. result.m[3] = 0.0;
  5879. result.m[4] = 0.0;
  5880. result.m[7] = 0.0;
  5881. result.m[8] = 0.0;
  5882. result.m[11] = 0.0;
  5883. result.m[12] = 0.0;
  5884. result.m[13] = 0.0;
  5885. result.m[14] = 0.0;
  5886. result._markAsUpdated();
  5887. };
  5888. /**
  5889. * Creates a new rotation matrix for "angle" radians around the Y axis
  5890. * @param angle defines the angle (in radians) to use
  5891. * @return the new matrix
  5892. */
  5893. Matrix.RotationY = function (angle) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYToRef(angle, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5900. * @param angle defines the angle (in radians) to use
  5901. * @param result defines the target matrix
  5902. */
  5903. Matrix.RotationYToRef = function (angle, result) {
  5904. var s = Math.sin(angle);
  5905. var c = Math.cos(angle);
  5906. result.m[5] = 1.0;
  5907. result.m[15] = 1.0;
  5908. result.m[0] = c;
  5909. result.m[2] = -s;
  5910. result.m[8] = s;
  5911. result.m[10] = c;
  5912. result.m[1] = 0.0;
  5913. result.m[3] = 0.0;
  5914. result.m[4] = 0.0;
  5915. result.m[6] = 0.0;
  5916. result.m[7] = 0.0;
  5917. result.m[9] = 0.0;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result._markAsUpdated();
  5923. };
  5924. /**
  5925. * Creates a new rotation matrix for "angle" radians around the Z axis
  5926. * @param angle defines the angle (in radians) to use
  5927. * @return the new matrix
  5928. */
  5929. Matrix.RotationZ = function (angle) {
  5930. var result = new Matrix();
  5931. Matrix.RotationZToRef(angle, result);
  5932. return result;
  5933. };
  5934. /**
  5935. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5936. * @param angle defines the angle (in radians) to use
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.RotationZToRef = function (angle, result) {
  5940. var s = Math.sin(angle);
  5941. var c = Math.cos(angle);
  5942. result.m[10] = 1.0;
  5943. result.m[15] = 1.0;
  5944. result.m[0] = c;
  5945. result.m[1] = s;
  5946. result.m[4] = -s;
  5947. result.m[5] = c;
  5948. result.m[2] = 0.0;
  5949. result.m[3] = 0.0;
  5950. result.m[6] = 0.0;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = 0.0;
  5953. result.m[9] = 0.0;
  5954. result.m[11] = 0.0;
  5955. result.m[12] = 0.0;
  5956. result.m[13] = 0.0;
  5957. result.m[14] = 0.0;
  5958. result._markAsUpdated();
  5959. };
  5960. /**
  5961. * Creates a new rotation matrix for "angle" radians around the given axis
  5962. * @param axis defines the axis to use
  5963. * @param angle defines the angle (in radians) to use
  5964. * @return the new matrix
  5965. */
  5966. Matrix.RotationAxis = function (axis, angle) {
  5967. var result = Matrix.Zero();
  5968. Matrix.RotationAxisToRef(axis, angle, result);
  5969. return result;
  5970. };
  5971. /**
  5972. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5973. * @param axis defines the axis to use
  5974. * @param angle defines the angle (in radians) to use
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5978. var s = Math.sin(-angle);
  5979. var c = Math.cos(-angle);
  5980. var c1 = 1 - c;
  5981. axis.normalize();
  5982. result.m[0] = (axis.x * axis.x) * c1 + c;
  5983. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5984. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5985. result.m[3] = 0.0;
  5986. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5987. result.m[5] = (axis.y * axis.y) * c1 + c;
  5988. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5989. result.m[7] = 0.0;
  5990. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5991. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5992. result.m[10] = (axis.z * axis.z) * c1 + c;
  5993. result.m[11] = 0.0;
  5994. result.m[15] = 1.0;
  5995. result._markAsUpdated();
  5996. };
  5997. /**
  5998. * Creates a rotation matrix
  5999. * @param yaw defines the yaw angle in radians (Y axis)
  6000. * @param pitch defines the pitch angle in radians (X axis)
  6001. * @param roll defines the roll angle in radians (X axis)
  6002. * @returns the new rotation matrix
  6003. */
  6004. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6005. var result = new Matrix();
  6006. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Creates a rotation matrix and stores it in a given matrix
  6011. * @param yaw defines the yaw angle in radians (Y axis)
  6012. * @param pitch defines the pitch angle in radians (X axis)
  6013. * @param roll defines the roll angle in radians (X axis)
  6014. * @param result defines the target matrix
  6015. */
  6016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6018. this._tempQuaternion.toRotationMatrix(result);
  6019. };
  6020. /**
  6021. * Creates a scaling matrix
  6022. * @param x defines the scale factor on X axis
  6023. * @param y defines the scale factor on Y axis
  6024. * @param z defines the scale factor on Z axis
  6025. * @returns the new matrix
  6026. */
  6027. Matrix.Scaling = function (x, y, z) {
  6028. var result = Matrix.Zero();
  6029. Matrix.ScalingToRef(x, y, z, result);
  6030. return result;
  6031. };
  6032. /**
  6033. * Creates a scaling matrix and stores it in a given matrix
  6034. * @param x defines the scale factor on X axis
  6035. * @param y defines the scale factor on Y axis
  6036. * @param z defines the scale factor on Z axis
  6037. * @param result defines the target matrix
  6038. */
  6039. Matrix.ScalingToRef = function (x, y, z, result) {
  6040. result.m[0] = x;
  6041. result.m[1] = 0.0;
  6042. result.m[2] = 0.0;
  6043. result.m[3] = 0.0;
  6044. result.m[4] = 0.0;
  6045. result.m[5] = y;
  6046. result.m[6] = 0.0;
  6047. result.m[7] = 0.0;
  6048. result.m[8] = 0.0;
  6049. result.m[9] = 0.0;
  6050. result.m[10] = z;
  6051. result.m[11] = 0.0;
  6052. result.m[12] = 0.0;
  6053. result.m[13] = 0.0;
  6054. result.m[14] = 0.0;
  6055. result.m[15] = 1.0;
  6056. result._markAsUpdated();
  6057. };
  6058. /**
  6059. * Creates a translation matrix
  6060. * @param x defines the translation on X axis
  6061. * @param y defines the translation on Y axis
  6062. * @param z defines the translationon Z axis
  6063. * @returns the new matrix
  6064. */
  6065. Matrix.Translation = function (x, y, z) {
  6066. var result = Matrix.Identity();
  6067. Matrix.TranslationToRef(x, y, z, result);
  6068. return result;
  6069. };
  6070. /**
  6071. * Creates a translation matrix and stores it in a given matrix
  6072. * @param x defines the translation on X axis
  6073. * @param y defines the translation on Y axis
  6074. * @param z defines the translationon Z axis
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.TranslationToRef = function (x, y, z, result) {
  6078. 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);
  6079. };
  6080. /**
  6081. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6082. * @param startValue defines the start value
  6083. * @param endValue defines the end value
  6084. * @param gradient defines the gradient factor
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.Lerp = function (startValue, endValue, gradient) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6094. * @param startValue defines the start value
  6095. * @param endValue defines the end value
  6096. * @param gradient defines the gradient factor
  6097. * @param result defines the Matrix object where to store data
  6098. */
  6099. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6100. for (var index = 0; index < 16; index++) {
  6101. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6102. }
  6103. result._markAsUpdated();
  6104. };
  6105. /**
  6106. * Builds a new matrix whose values are computed by:
  6107. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6108. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6109. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6110. * @param startValue defines the first matrix
  6111. * @param endValue defines the second matrix
  6112. * @param gradient defines the gradient between the two matrices
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6116. var result = Matrix.Zero();
  6117. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Update a matrix to values which are computed by:
  6122. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6123. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6124. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6125. * @param startValue defines the first matrix
  6126. * @param endValue defines the second matrix
  6127. * @param gradient defines the gradient between the two matrices
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6131. var startScale = MathTmp.Vector3[0];
  6132. var startRotation = MathTmp.Quaternion[0];
  6133. var startTranslation = MathTmp.Vector3[1];
  6134. startValue.decompose(startScale, startRotation, startTranslation);
  6135. var endScale = MathTmp.Vector3[2];
  6136. var endRotation = MathTmp.Quaternion[1];
  6137. var endTranslation = MathTmp.Vector3[3];
  6138. endValue.decompose(endScale, endRotation, endTranslation);
  6139. var resultScale = MathTmp.Vector3[4];
  6140. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6141. var resultRotation = MathTmp.Quaternion[2];
  6142. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6143. var resultTranslation = MathTmp.Vector3[5];
  6144. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6145. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6146. };
  6147. /**
  6148. * 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"
  6149. * This function works in left handed mode
  6150. * @param eye defines the final position of the entity
  6151. * @param target defines where the entity should look at
  6152. * @param up defines the up vector for the entity
  6153. * @returns the new matrix
  6154. */
  6155. Matrix.LookAtLH = function (eye, target, up) {
  6156. var result = Matrix.Zero();
  6157. Matrix.LookAtLHToRef(eye, target, up, result);
  6158. return result;
  6159. };
  6160. /**
  6161. * 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".
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6169. // Z axis
  6170. target.subtractToRef(eye, this._zAxis);
  6171. this._zAxis.normalize();
  6172. // X axis
  6173. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6174. if (this._xAxis.lengthSquared() === 0) {
  6175. this._xAxis.x = 1.0;
  6176. }
  6177. else {
  6178. this._xAxis.normalize();
  6179. }
  6180. // Y axis
  6181. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6182. this._yAxis.normalize();
  6183. // Eye angles
  6184. var ex = -Vector3.Dot(this._xAxis, eye);
  6185. var ey = -Vector3.Dot(this._yAxis, eye);
  6186. var ez = -Vector3.Dot(this._zAxis, eye);
  6187. 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);
  6188. };
  6189. /**
  6190. * 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"
  6191. * This function works in right handed mode
  6192. * @param eye defines the final position of the entity
  6193. * @param target defines where the entity should look at
  6194. * @param up defines the up vector for the entity
  6195. * @returns the new matrix
  6196. */
  6197. Matrix.LookAtRH = function (eye, target, up) {
  6198. var result = Matrix.Zero();
  6199. Matrix.LookAtRHToRef(eye, target, up, result);
  6200. return result;
  6201. };
  6202. /**
  6203. * 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".
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @param result defines the target matrix
  6209. */
  6210. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6211. // Z axis
  6212. eye.subtractToRef(target, this._zAxis);
  6213. this._zAxis.normalize();
  6214. // X axis
  6215. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6216. if (this._xAxis.lengthSquared() === 0) {
  6217. this._xAxis.x = 1.0;
  6218. }
  6219. else {
  6220. this._xAxis.normalize();
  6221. }
  6222. // Y axis
  6223. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6224. this._yAxis.normalize();
  6225. // Eye angles
  6226. var ex = -Vector3.Dot(this._xAxis, eye);
  6227. var ey = -Vector3.Dot(this._yAxis, eye);
  6228. var ez = -Vector3.Dot(this._zAxis, eye);
  6229. 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);
  6230. };
  6231. /**
  6232. * Create a left-handed orthographic projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Store a left-handed orthographic projection to a given matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @param result defines the target matrix
  6251. */
  6252. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6253. var n = znear;
  6254. var f = zfar;
  6255. var a = 2.0 / width;
  6256. var b = 2.0 / height;
  6257. var c = 2.0 / (f - n);
  6258. var d = -(f + n) / (f - n);
  6259. 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);
  6260. };
  6261. /**
  6262. * Create a left-handed orthographic projection matrix
  6263. * @param left defines the viewport left coordinate
  6264. * @param right defines the viewport right coordinate
  6265. * @param bottom defines the viewport bottom coordinate
  6266. * @param top defines the viewport top coordinate
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @returns a new matrix as a left-handed orthographic projection matrix
  6270. */
  6271. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6272. var matrix = Matrix.Zero();
  6273. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6274. return matrix;
  6275. };
  6276. /**
  6277. * Stores a left-handed orthographic projection into a given matrix
  6278. * @param left defines the viewport left coordinate
  6279. * @param right defines the viewport right coordinate
  6280. * @param bottom defines the viewport bottom coordinate
  6281. * @param top defines the viewport top coordinate
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6287. var n = znear;
  6288. var f = zfar;
  6289. var a = 2.0 / (right - left);
  6290. var b = 2.0 / (top - bottom);
  6291. var c = 2.0 / (f - n);
  6292. var d = -(f + n) / (f - n);
  6293. var i0 = (left + right) / (left - right);
  6294. var i1 = (top + bottom) / (bottom - top);
  6295. 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);
  6296. };
  6297. /**
  6298. * Creates a right-handed orthographic projection matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a right-handed orthographic projection matrix
  6306. */
  6307. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6310. return matrix;
  6311. };
  6312. /**
  6313. * Stores a right-handed orthographic projection into a given matrix
  6314. * @param left defines the viewport left coordinate
  6315. * @param right defines the viewport right coordinate
  6316. * @param bottom defines the viewport bottom coordinate
  6317. * @param top defines the viewport top coordinate
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. */
  6322. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6323. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6324. result.m[10] *= -1.0;
  6325. };
  6326. /**
  6327. * Creates a left-handed perspective projection matrix
  6328. * @param width defines the viewport width
  6329. * @param height defines the viewport height
  6330. * @param znear defines the near clip plane
  6331. * @param zfar defines the far clip plane
  6332. * @returns a new matrix as a left-handed perspective projection matrix
  6333. */
  6334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6335. var matrix = Matrix.Zero();
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 * n / width;
  6339. var b = 2.0 * n / height;
  6340. var c = (f + n) / (f - n);
  6341. var d = -2.0 * f * n / (f - n);
  6342. 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);
  6343. return matrix;
  6344. };
  6345. /**
  6346. * Creates a left-handed perspective projection matrix
  6347. * @param fov defines the horizontal field of view
  6348. * @param aspect defines the aspect ratio
  6349. * @param znear defines the near clip plane
  6350. * @param zfar defines the far clip plane
  6351. * @returns a new matrix as a left-handed perspective projection matrix
  6352. */
  6353. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6354. var matrix = Matrix.Zero();
  6355. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Stores a left-handed perspective projection into a given matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @param result defines the target matrix
  6365. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6366. */
  6367. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6368. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6369. var n = znear;
  6370. var f = zfar;
  6371. var t = 1.0 / (Math.tan(fov * 0.5));
  6372. var a = isVerticalFovFixed ? (t / aspect) : t;
  6373. var b = isVerticalFovFixed ? t : (t * aspect);
  6374. var c = (f + n) / (f - n);
  6375. var d = -2.0 * f * n / (f - n);
  6376. 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);
  6377. };
  6378. /**
  6379. * Creates a right-handed perspective projection matrix
  6380. * @param fov defines the horizontal field of view
  6381. * @param aspect defines the aspect ratio
  6382. * @param znear defines the near clip plane
  6383. * @param zfar defines the far clip plane
  6384. * @returns a new matrix as a right-handed perspective projection matrix
  6385. */
  6386. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6387. var matrix = Matrix.Zero();
  6388. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6389. return matrix;
  6390. };
  6391. /**
  6392. * Stores a right-handed perspective projection into a given matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @param result defines the target matrix
  6398. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6399. */
  6400. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6401. //alternatively this could be expressed as:
  6402. // m = PerspectiveFovLHToRef
  6403. // m[10] *= -1.0;
  6404. // m[11] *= -1.0;
  6405. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6406. var n = znear;
  6407. var f = zfar;
  6408. var t = 1.0 / (Math.tan(fov * 0.5));
  6409. var a = isVerticalFovFixed ? (t / aspect) : t;
  6410. var b = isVerticalFovFixed ? t : (t * aspect);
  6411. var c = -(f + n) / (f - n);
  6412. var d = -2 * f * n / (f - n);
  6413. 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);
  6414. };
  6415. /**
  6416. * Stores a perspective projection for WebVR info a given matrix
  6417. * @param fov defines the field of view
  6418. * @param znear defines the near clip plane
  6419. * @param zfar defines the far clip plane
  6420. * @param result defines the target matrix
  6421. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6422. */
  6423. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6424. if (rightHanded === void 0) { rightHanded = false; }
  6425. var rightHandedFactor = rightHanded ? -1 : 1;
  6426. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6427. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6428. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6429. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6430. var xScale = 2.0 / (leftTan + rightTan);
  6431. var yScale = 2.0 / (upTan + downTan);
  6432. result.m[0] = xScale;
  6433. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6434. result.m[5] = yScale;
  6435. result.m[6] = result.m[7] = 0.0;
  6436. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6437. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6438. result.m[10] = -zfar / (znear - zfar);
  6439. result.m[11] = 1.0 * rightHandedFactor;
  6440. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6441. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6442. result._markAsUpdated();
  6443. };
  6444. /**
  6445. * Computes a complete transformation matrix
  6446. * @param viewport defines the viewport to use
  6447. * @param world defines the world matrix
  6448. * @param view defines the view matrix
  6449. * @param projection defines the projection matrix
  6450. * @param zmin defines the near clip plane
  6451. * @param zmax defines the far clip plane
  6452. * @returns the transformation matrix
  6453. */
  6454. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6455. var cw = viewport.width;
  6456. var ch = viewport.height;
  6457. var cx = viewport.x;
  6458. var cy = viewport.y;
  6459. 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);
  6460. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6461. };
  6462. /**
  6463. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6464. * @param matrix defines the matrix to use
  6465. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6466. */
  6467. Matrix.GetAsMatrix2x2 = function (matrix) {
  6468. return new Float32Array([
  6469. matrix.m[0], matrix.m[1],
  6470. matrix.m[4], matrix.m[5]
  6471. ]);
  6472. };
  6473. /**
  6474. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6475. * @param matrix defines the matrix to use
  6476. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6477. */
  6478. Matrix.GetAsMatrix3x3 = function (matrix) {
  6479. return new Float32Array([
  6480. matrix.m[0], matrix.m[1], matrix.m[2],
  6481. matrix.m[4], matrix.m[5], matrix.m[6],
  6482. matrix.m[8], matrix.m[9], matrix.m[10]
  6483. ]);
  6484. };
  6485. /**
  6486. * Compute the transpose of a given matrix
  6487. * @param matrix defines the matrix to transpose
  6488. * @returns the new matrix
  6489. */
  6490. Matrix.Transpose = function (matrix) {
  6491. var result = new Matrix();
  6492. Matrix.TransposeToRef(matrix, result);
  6493. return result;
  6494. };
  6495. /**
  6496. * Compute the transpose of a matrix and store it in a target matrix
  6497. * @param matrix defines the matrix to transpose
  6498. * @param result defines the target matrix
  6499. */
  6500. Matrix.TransposeToRef = function (matrix, result) {
  6501. result.m[0] = matrix.m[0];
  6502. result.m[1] = matrix.m[4];
  6503. result.m[2] = matrix.m[8];
  6504. result.m[3] = matrix.m[12];
  6505. result.m[4] = matrix.m[1];
  6506. result.m[5] = matrix.m[5];
  6507. result.m[6] = matrix.m[9];
  6508. result.m[7] = matrix.m[13];
  6509. result.m[8] = matrix.m[2];
  6510. result.m[9] = matrix.m[6];
  6511. result.m[10] = matrix.m[10];
  6512. result.m[11] = matrix.m[14];
  6513. result.m[12] = matrix.m[3];
  6514. result.m[13] = matrix.m[7];
  6515. result.m[14] = matrix.m[11];
  6516. result.m[15] = matrix.m[15];
  6517. };
  6518. /**
  6519. * Computes a reflection matrix from a plane
  6520. * @param plane defines the reflection plane
  6521. * @returns a new matrix
  6522. */
  6523. Matrix.Reflection = function (plane) {
  6524. var matrix = new Matrix();
  6525. Matrix.ReflectionToRef(plane, matrix);
  6526. return matrix;
  6527. };
  6528. /**
  6529. * Computes a reflection matrix from a plane
  6530. * @param plane defines the reflection plane
  6531. * @param result defines the target matrix
  6532. */
  6533. Matrix.ReflectionToRef = function (plane, result) {
  6534. plane.normalize();
  6535. var x = plane.normal.x;
  6536. var y = plane.normal.y;
  6537. var z = plane.normal.z;
  6538. var temp = -2 * x;
  6539. var temp2 = -2 * y;
  6540. var temp3 = -2 * z;
  6541. result.m[0] = (temp * x) + 1;
  6542. result.m[1] = temp2 * x;
  6543. result.m[2] = temp3 * x;
  6544. result.m[3] = 0.0;
  6545. result.m[4] = temp * y;
  6546. result.m[5] = (temp2 * y) + 1;
  6547. result.m[6] = temp3 * y;
  6548. result.m[7] = 0.0;
  6549. result.m[8] = temp * z;
  6550. result.m[9] = temp2 * z;
  6551. result.m[10] = (temp3 * z) + 1;
  6552. result.m[11] = 0.0;
  6553. result.m[12] = temp * plane.d;
  6554. result.m[13] = temp2 * plane.d;
  6555. result.m[14] = temp3 * plane.d;
  6556. result.m[15] = 1.0;
  6557. result._markAsUpdated();
  6558. };
  6559. /**
  6560. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6561. * @param xaxis defines the value of the 1st axis
  6562. * @param yaxis defines the value of the 2nd axis
  6563. * @param zaxis defines the value of the 3rd axis
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6567. result.m[0] = xaxis.x;
  6568. result.m[1] = xaxis.y;
  6569. result.m[2] = xaxis.z;
  6570. result.m[3] = 0.0;
  6571. result.m[4] = yaxis.x;
  6572. result.m[5] = yaxis.y;
  6573. result.m[6] = yaxis.z;
  6574. result.m[7] = 0.0;
  6575. result.m[8] = zaxis.x;
  6576. result.m[9] = zaxis.y;
  6577. result.m[10] = zaxis.z;
  6578. result.m[11] = 0.0;
  6579. result.m[12] = 0.0;
  6580. result.m[13] = 0.0;
  6581. result.m[14] = 0.0;
  6582. result.m[15] = 1.0;
  6583. result._markAsUpdated();
  6584. };
  6585. /**
  6586. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6587. * @param quat defines the quaternion to use
  6588. * @param result defines the target matrix
  6589. */
  6590. Matrix.FromQuaternionToRef = function (quat, result) {
  6591. var xx = quat.x * quat.x;
  6592. var yy = quat.y * quat.y;
  6593. var zz = quat.z * quat.z;
  6594. var xy = quat.x * quat.y;
  6595. var zw = quat.z * quat.w;
  6596. var zx = quat.z * quat.x;
  6597. var yw = quat.y * quat.w;
  6598. var yz = quat.y * quat.z;
  6599. var xw = quat.x * quat.w;
  6600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6601. result.m[1] = 2.0 * (xy + zw);
  6602. result.m[2] = 2.0 * (zx - yw);
  6603. result.m[3] = 0.0;
  6604. result.m[4] = 2.0 * (xy - zw);
  6605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6606. result.m[6] = 2.0 * (yz + xw);
  6607. result.m[7] = 0.0;
  6608. result.m[8] = 2.0 * (zx + yw);
  6609. result.m[9] = 2.0 * (yz - xw);
  6610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6611. result.m[11] = 0.0;
  6612. result.m[12] = 0.0;
  6613. result.m[13] = 0.0;
  6614. result.m[14] = 0.0;
  6615. result.m[15] = 1.0;
  6616. result._markAsUpdated();
  6617. };
  6618. Matrix._tempQuaternion = new Quaternion();
  6619. Matrix._xAxis = Vector3.Zero();
  6620. Matrix._yAxis = Vector3.Zero();
  6621. Matrix._zAxis = Vector3.Zero();
  6622. Matrix._updateFlagSeed = 0;
  6623. Matrix._identityReadOnly = Matrix.Identity();
  6624. return Matrix;
  6625. }());
  6626. BABYLON.Matrix = Matrix;
  6627. var Plane = /** @class */ (function () {
  6628. /**
  6629. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6630. */
  6631. function Plane(a, b, c, d) {
  6632. this.normal = new Vector3(a, b, c);
  6633. this.d = d;
  6634. }
  6635. /**
  6636. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6637. */
  6638. Plane.prototype.asArray = function () {
  6639. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6640. };
  6641. // Methods
  6642. /**
  6643. * Returns a new plane copied from the current Plane.
  6644. */
  6645. Plane.prototype.clone = function () {
  6646. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6647. };
  6648. /**
  6649. * Returns the string "Plane".
  6650. */
  6651. Plane.prototype.getClassName = function () {
  6652. return "Plane";
  6653. };
  6654. /**
  6655. * Returns the Plane hash code.
  6656. */
  6657. Plane.prototype.getHashCode = function () {
  6658. var hash = this.normal.getHashCode();
  6659. hash = (hash * 397) ^ (this.d || 0);
  6660. return hash;
  6661. };
  6662. /**
  6663. * Normalize the current Plane in place.
  6664. * Returns the updated Plane.
  6665. */
  6666. Plane.prototype.normalize = function () {
  6667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6668. var magnitude = 0.0;
  6669. if (norm !== 0) {
  6670. magnitude = 1.0 / norm;
  6671. }
  6672. this.normal.x *= magnitude;
  6673. this.normal.y *= magnitude;
  6674. this.normal.z *= magnitude;
  6675. this.d *= magnitude;
  6676. return this;
  6677. };
  6678. /**
  6679. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6680. */
  6681. Plane.prototype.transform = function (transformation) {
  6682. var transposedMatrix = Matrix.Transpose(transformation);
  6683. var x = this.normal.x;
  6684. var y = this.normal.y;
  6685. var z = this.normal.z;
  6686. var d = this.d;
  6687. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6688. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6689. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6690. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6691. return new Plane(normalX, normalY, normalZ, finalD);
  6692. };
  6693. /**
  6694. * Returns the dot product (float) of the point coordinates and the plane normal.
  6695. */
  6696. Plane.prototype.dotCoordinate = function (point) {
  6697. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6698. };
  6699. /**
  6700. * Updates the current Plane from the plane defined by the three given points.
  6701. * Returns the updated Plane.
  6702. */
  6703. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6704. var x1 = point2.x - point1.x;
  6705. var y1 = point2.y - point1.y;
  6706. var z1 = point2.z - point1.z;
  6707. var x2 = point3.x - point1.x;
  6708. var y2 = point3.y - point1.y;
  6709. var z2 = point3.z - point1.z;
  6710. var yz = (y1 * z2) - (z1 * y2);
  6711. var xz = (z1 * x2) - (x1 * z2);
  6712. var xy = (x1 * y2) - (y1 * x2);
  6713. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6714. var invPyth;
  6715. if (pyth !== 0) {
  6716. invPyth = 1.0 / pyth;
  6717. }
  6718. else {
  6719. invPyth = 0.0;
  6720. }
  6721. this.normal.x = yz * invPyth;
  6722. this.normal.y = xz * invPyth;
  6723. this.normal.z = xy * invPyth;
  6724. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6725. return this;
  6726. };
  6727. /**
  6728. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6729. */
  6730. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6731. var dot = Vector3.Dot(this.normal, direction);
  6732. return (dot <= epsilon);
  6733. };
  6734. /**
  6735. * Returns the signed distance (float) from the given point to the Plane.
  6736. */
  6737. Plane.prototype.signedDistanceTo = function (point) {
  6738. return Vector3.Dot(point, this.normal) + this.d;
  6739. };
  6740. // Statics
  6741. /**
  6742. * Returns a new Plane from the given array.
  6743. */
  6744. Plane.FromArray = function (array) {
  6745. return new Plane(array[0], array[1], array[2], array[3]);
  6746. };
  6747. /**
  6748. * Returns a new Plane defined by the three given points.
  6749. */
  6750. Plane.FromPoints = function (point1, point2, point3) {
  6751. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6752. result.copyFromPoints(point1, point2, point3);
  6753. return result;
  6754. };
  6755. /**
  6756. * Returns a new Plane the normal vector to this plane at the given origin point.
  6757. * Note : the vector "normal" is updated because normalized.
  6758. */
  6759. Plane.FromPositionAndNormal = function (origin, normal) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. normal.normalize();
  6762. result.normal = normal;
  6763. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6764. return result;
  6765. };
  6766. /**
  6767. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6768. */
  6769. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6770. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6771. return Vector3.Dot(point, normal) + d;
  6772. };
  6773. return Plane;
  6774. }());
  6775. BABYLON.Plane = Plane;
  6776. var Viewport = /** @class */ (function () {
  6777. /**
  6778. * Creates a Viewport object located at (x, y) and sized (width, height).
  6779. */
  6780. function Viewport(x, y, width, height) {
  6781. this.x = x;
  6782. this.y = y;
  6783. this.width = width;
  6784. this.height = height;
  6785. }
  6786. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6787. if (renderWidthOrEngine.getRenderWidth) {
  6788. var engine = renderWidthOrEngine;
  6789. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6790. }
  6791. var renderWidth = renderWidthOrEngine;
  6792. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6793. };
  6794. /**
  6795. * Returns a new Viewport copied from the current one.
  6796. */
  6797. Viewport.prototype.clone = function () {
  6798. return new Viewport(this.x, this.y, this.width, this.height);
  6799. };
  6800. return Viewport;
  6801. }());
  6802. BABYLON.Viewport = Viewport;
  6803. var Frustum = /** @class */ (function () {
  6804. function Frustum() {
  6805. }
  6806. /**
  6807. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6808. */
  6809. Frustum.GetPlanes = function (transform) {
  6810. var frustumPlanes = [];
  6811. for (var index = 0; index < 6; index++) {
  6812. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6813. }
  6814. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6815. return frustumPlanes;
  6816. };
  6817. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6818. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6819. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6820. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6821. frustumPlane.d = transform.m[15] + transform.m[14];
  6822. frustumPlane.normalize();
  6823. };
  6824. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6825. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6826. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6827. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6828. frustumPlane.d = transform.m[15] - transform.m[14];
  6829. frustumPlane.normalize();
  6830. };
  6831. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6835. frustumPlane.d = transform.m[15] + transform.m[12];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6842. frustumPlane.d = transform.m[15] - transform.m[12];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6849. frustumPlane.d = transform.m[15] - transform.m[13];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6856. frustumPlane.d = transform.m[15] + transform.m[13];
  6857. frustumPlane.normalize();
  6858. };
  6859. /**
  6860. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6861. */
  6862. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6863. // Near
  6864. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6865. // Far
  6866. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6867. // Left
  6868. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6869. // Right
  6870. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6871. // Top
  6872. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6873. // Bottom
  6874. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6875. };
  6876. return Frustum;
  6877. }());
  6878. BABYLON.Frustum = Frustum;
  6879. /** Defines supported spaces */
  6880. var Space;
  6881. (function (Space) {
  6882. /** Local (object) space */
  6883. Space[Space["LOCAL"] = 0] = "LOCAL";
  6884. /** World space */
  6885. Space[Space["WORLD"] = 1] = "WORLD";
  6886. /** Bone space */
  6887. Space[Space["BONE"] = 2] = "BONE";
  6888. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6889. /** Defines the 3 main axes */
  6890. var Axis = /** @class */ (function () {
  6891. function Axis() {
  6892. }
  6893. /** X axis */
  6894. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6895. /** Y axis */
  6896. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6897. /** Z axis */
  6898. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6899. return Axis;
  6900. }());
  6901. BABYLON.Axis = Axis;
  6902. ;
  6903. var BezierCurve = /** @class */ (function () {
  6904. function BezierCurve() {
  6905. }
  6906. /**
  6907. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6908. */
  6909. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6910. // Extract X (which is equal to time here)
  6911. var f0 = 1 - 3 * x2 + 3 * x1;
  6912. var f1 = 3 * x2 - 6 * x1;
  6913. var f2 = 3 * x1;
  6914. var refinedT = t;
  6915. for (var i = 0; i < 5; i++) {
  6916. var refinedT2 = refinedT * refinedT;
  6917. var refinedT3 = refinedT2 * refinedT;
  6918. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6919. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6920. refinedT -= (x - t) * slope;
  6921. refinedT = Math.min(1, Math.max(0, refinedT));
  6922. }
  6923. // Resolve cubic bezier for the given x
  6924. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6925. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6926. Math.pow(refinedT, 3);
  6927. };
  6928. return BezierCurve;
  6929. }());
  6930. BABYLON.BezierCurve = BezierCurve;
  6931. /**
  6932. * Defines potential orientation for back face culling
  6933. */
  6934. var Orientation;
  6935. (function (Orientation) {
  6936. /**
  6937. * Clockwise
  6938. */
  6939. Orientation[Orientation["CW"] = 0] = "CW";
  6940. /** Counter clockwise */
  6941. Orientation[Orientation["CCW"] = 1] = "CCW";
  6942. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6943. /**
  6944. * Defines angle representation
  6945. */
  6946. var Angle = /** @class */ (function () {
  6947. /**
  6948. * Creates an Angle object of "radians" radians (float).
  6949. */
  6950. function Angle(radians) {
  6951. this._radians = radians;
  6952. if (this._radians < 0.0)
  6953. this._radians += (2.0 * Math.PI);
  6954. }
  6955. /**
  6956. * Get value in degrees
  6957. * @returns the Angle value in degrees (float)
  6958. */
  6959. Angle.prototype.degrees = function () {
  6960. return this._radians * 180.0 / Math.PI;
  6961. };
  6962. /**
  6963. * Get value in radians
  6964. * @returns the Angle value in radians (float)
  6965. */
  6966. Angle.prototype.radians = function () {
  6967. return this._radians;
  6968. };
  6969. /**
  6970. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6971. * @param a defines first vector
  6972. * @param b defines second vector
  6973. * @returns a new Angle
  6974. */
  6975. Angle.BetweenTwoPoints = function (a, b) {
  6976. var delta = b.subtract(a);
  6977. var theta = Math.atan2(delta.y, delta.x);
  6978. return new Angle(theta);
  6979. };
  6980. /**
  6981. * Gets a new Angle object from the given float in radians
  6982. * @param radians defines the angle value in radians
  6983. * @returns a new Angle
  6984. */
  6985. Angle.FromRadians = function (radians) {
  6986. return new Angle(radians);
  6987. };
  6988. /**
  6989. * Gets a new Angle object from the given float in degrees
  6990. * @param degrees defines the angle value in degrees
  6991. * @returns a new Angle
  6992. */
  6993. Angle.FromDegrees = function (degrees) {
  6994. return new Angle(degrees * Math.PI / 180.0);
  6995. };
  6996. return Angle;
  6997. }());
  6998. BABYLON.Angle = Angle;
  6999. var Arc2 = /** @class */ (function () {
  7000. /**
  7001. * Creates an Arc object from the three given points : start, middle and end.
  7002. */
  7003. function Arc2(startPoint, midPoint, endPoint) {
  7004. this.startPoint = startPoint;
  7005. this.midPoint = midPoint;
  7006. this.endPoint = endPoint;
  7007. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7008. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7009. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7010. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7011. 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);
  7012. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7013. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7014. var a1 = this.startAngle.degrees();
  7015. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7016. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7017. // angles correction
  7018. if (a2 - a1 > +180.0)
  7019. a2 -= 360.0;
  7020. if (a2 - a1 < -180.0)
  7021. a2 += 360.0;
  7022. if (a3 - a2 > +180.0)
  7023. a3 -= 360.0;
  7024. if (a3 - a2 < -180.0)
  7025. a3 += 360.0;
  7026. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7027. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7028. }
  7029. return Arc2;
  7030. }());
  7031. BABYLON.Arc2 = Arc2;
  7032. var Path2 = /** @class */ (function () {
  7033. /**
  7034. * Creates a Path2 object from the starting 2D coordinates x and y.
  7035. */
  7036. function Path2(x, y) {
  7037. this._points = new Array();
  7038. this._length = 0.0;
  7039. this.closed = false;
  7040. this._points.push(new Vector2(x, y));
  7041. }
  7042. /**
  7043. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7044. * Returns the updated Path2.
  7045. */
  7046. Path2.prototype.addLineTo = function (x, y) {
  7047. if (this.closed) {
  7048. return this;
  7049. }
  7050. var newPoint = new Vector2(x, y);
  7051. var previousPoint = this._points[this._points.length - 1];
  7052. this._points.push(newPoint);
  7053. this._length += newPoint.subtract(previousPoint).length();
  7054. return this;
  7055. };
  7056. /**
  7057. * 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.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7061. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7062. if (this.closed) {
  7063. return this;
  7064. }
  7065. var startPoint = this._points[this._points.length - 1];
  7066. var midPoint = new Vector2(midX, midY);
  7067. var endPoint = new Vector2(endX, endY);
  7068. var arc = new Arc2(startPoint, midPoint, endPoint);
  7069. var increment = arc.angle.radians() / numberOfSegments;
  7070. if (arc.orientation === Orientation.CW)
  7071. increment *= -1;
  7072. var currentAngle = arc.startAngle.radians() + increment;
  7073. for (var i = 0; i < numberOfSegments; i++) {
  7074. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7075. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7076. this.addLineTo(x, y);
  7077. currentAngle += increment;
  7078. }
  7079. return this;
  7080. };
  7081. /**
  7082. * Closes the Path2.
  7083. * Returns the Path2.
  7084. */
  7085. Path2.prototype.close = function () {
  7086. this.closed = true;
  7087. return this;
  7088. };
  7089. /**
  7090. * Returns the Path2 total length (float).
  7091. */
  7092. Path2.prototype.length = function () {
  7093. var result = this._length;
  7094. if (!this.closed) {
  7095. var lastPoint = this._points[this._points.length - 1];
  7096. var firstPoint = this._points[0];
  7097. result += (firstPoint.subtract(lastPoint).length());
  7098. }
  7099. return result;
  7100. };
  7101. /**
  7102. * Returns the Path2 internal array of points.
  7103. */
  7104. Path2.prototype.getPoints = function () {
  7105. return this._points;
  7106. };
  7107. /**
  7108. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7109. */
  7110. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7111. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7112. return Vector2.Zero();
  7113. }
  7114. var lengthPosition = normalizedLengthPosition * this.length();
  7115. var previousOffset = 0;
  7116. for (var i = 0; i < this._points.length; i++) {
  7117. var j = (i + 1) % this._points.length;
  7118. var a = this._points[i];
  7119. var b = this._points[j];
  7120. var bToA = b.subtract(a);
  7121. var nextOffset = (bToA.length() + previousOffset);
  7122. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7123. var dir = bToA.normalize();
  7124. var localOffset = lengthPosition - previousOffset;
  7125. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7126. }
  7127. previousOffset = nextOffset;
  7128. }
  7129. return Vector2.Zero();
  7130. };
  7131. /**
  7132. * Returns a new Path2 starting at the coordinates (x, y).
  7133. */
  7134. Path2.StartingAt = function (x, y) {
  7135. return new Path2(x, y);
  7136. };
  7137. return Path2;
  7138. }());
  7139. BABYLON.Path2 = Path2;
  7140. var Path3D = /** @class */ (function () {
  7141. /**
  7142. * new Path3D(path, normal, raw)
  7143. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7144. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7145. * path : an array of Vector3, the curve axis of the Path3D
  7146. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7147. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7148. */
  7149. function Path3D(path, firstNormal, raw) {
  7150. if (firstNormal === void 0) { firstNormal = null; }
  7151. this.path = path;
  7152. this._curve = new Array();
  7153. this._distances = new Array();
  7154. this._tangents = new Array();
  7155. this._normals = new Array();
  7156. this._binormals = new Array();
  7157. for (var p = 0; p < path.length; p++) {
  7158. this._curve[p] = path[p].clone(); // hard copy
  7159. }
  7160. this._raw = raw || false;
  7161. this._compute(firstNormal);
  7162. }
  7163. /**
  7164. * Returns the Path3D array of successive Vector3 designing its curve.
  7165. */
  7166. Path3D.prototype.getCurve = function () {
  7167. return this._curve;
  7168. };
  7169. /**
  7170. * Returns an array populated with tangent vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getTangents = function () {
  7173. return this._tangents;
  7174. };
  7175. /**
  7176. * Returns an array populated with normal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getNormals = function () {
  7179. return this._normals;
  7180. };
  7181. /**
  7182. * Returns an array populated with binormal vectors on each Path3D curve point.
  7183. */
  7184. Path3D.prototype.getBinormals = function () {
  7185. return this._binormals;
  7186. };
  7187. /**
  7188. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7189. */
  7190. Path3D.prototype.getDistances = function () {
  7191. return this._distances;
  7192. };
  7193. /**
  7194. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7195. * Returns the same object updated.
  7196. */
  7197. Path3D.prototype.update = function (path, firstNormal) {
  7198. if (firstNormal === void 0) { firstNormal = null; }
  7199. for (var p = 0; p < path.length; p++) {
  7200. this._curve[p].x = path[p].x;
  7201. this._curve[p].y = path[p].y;
  7202. this._curve[p].z = path[p].z;
  7203. }
  7204. this._compute(firstNormal);
  7205. return this;
  7206. };
  7207. // private function compute() : computes tangents, normals and binormals
  7208. Path3D.prototype._compute = function (firstNormal) {
  7209. var l = this._curve.length;
  7210. // first and last tangents
  7211. this._tangents[0] = this._getFirstNonNullVector(0);
  7212. if (!this._raw) {
  7213. this._tangents[0].normalize();
  7214. }
  7215. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7216. if (!this._raw) {
  7217. this._tangents[l - 1].normalize();
  7218. }
  7219. // normals and binormals at first point : arbitrary vector with _normalVector()
  7220. var tg0 = this._tangents[0];
  7221. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7222. this._normals[0] = pp0;
  7223. if (!this._raw) {
  7224. this._normals[0].normalize();
  7225. }
  7226. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7227. if (!this._raw) {
  7228. this._binormals[0].normalize();
  7229. }
  7230. this._distances[0] = 0.0;
  7231. // normals and binormals : next points
  7232. var prev; // previous vector (segment)
  7233. var cur; // current vector (segment)
  7234. var curTang; // current tangent
  7235. // previous normal
  7236. var prevBinor; // previous binormal
  7237. for (var i = 1; i < l; i++) {
  7238. // tangents
  7239. prev = this._getLastNonNullVector(i);
  7240. if (i < l - 1) {
  7241. cur = this._getFirstNonNullVector(i);
  7242. this._tangents[i] = prev.add(cur);
  7243. this._tangents[i].normalize();
  7244. }
  7245. this._distances[i] = this._distances[i - 1] + prev.length();
  7246. // normals and binormals
  7247. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7248. curTang = this._tangents[i];
  7249. prevBinor = this._binormals[i - 1];
  7250. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7251. if (!this._raw) {
  7252. this._normals[i].normalize();
  7253. }
  7254. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7255. if (!this._raw) {
  7256. this._binormals[i].normalize();
  7257. }
  7258. }
  7259. };
  7260. // private function getFirstNonNullVector(index)
  7261. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7262. Path3D.prototype._getFirstNonNullVector = function (index) {
  7263. var i = 1;
  7264. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7266. i++;
  7267. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7268. }
  7269. return nNVector;
  7270. };
  7271. // private function getLastNonNullVector(index)
  7272. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7273. Path3D.prototype._getLastNonNullVector = function (index) {
  7274. var i = 1;
  7275. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. while (nLVector.length() === 0 && index > i + 1) {
  7277. i++;
  7278. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7279. }
  7280. return nLVector;
  7281. };
  7282. // private function normalVector(v0, vt, va) :
  7283. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7284. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7285. Path3D.prototype._normalVector = function (v0, vt, va) {
  7286. var normal0;
  7287. var tgl = vt.length();
  7288. if (tgl === 0.0) {
  7289. tgl = 1.0;
  7290. }
  7291. if (va === undefined || va === null) {
  7292. var point;
  7293. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7294. point = new Vector3(0.0, -1.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(1.0, 0.0, 0.0);
  7298. }
  7299. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7300. point = new Vector3(0.0, 0.0, 1.0);
  7301. }
  7302. else {
  7303. point = Vector3.Zero();
  7304. }
  7305. normal0 = Vector3.Cross(vt, point);
  7306. }
  7307. else {
  7308. normal0 = Vector3.Cross(vt, va);
  7309. Vector3.CrossToRef(normal0, vt, normal0);
  7310. }
  7311. normal0.normalize();
  7312. return normal0;
  7313. };
  7314. return Path3D;
  7315. }());
  7316. BABYLON.Path3D = Path3D;
  7317. var Curve3 = /** @class */ (function () {
  7318. /**
  7319. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7320. * A Curve3 is designed from a series of successive Vector3.
  7321. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7322. */
  7323. function Curve3(points) {
  7324. this._length = 0.0;
  7325. this._points = points;
  7326. this._length = this._computeLength(points);
  7327. }
  7328. /**
  7329. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7330. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7331. * @param v1 (Vector3) the control point
  7332. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7333. * @param nbPoints (integer) the wanted number of points in the curve
  7334. */
  7335. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7336. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7337. var bez = new Array();
  7338. var equation = function (t, val0, val1, val2) {
  7339. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7340. return res;
  7341. };
  7342. for (var i = 0; i <= nbPoints; i++) {
  7343. 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)));
  7344. }
  7345. return new Curve3(bez);
  7346. };
  7347. /**
  7348. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7349. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7350. * @param v1 (Vector3) the first control point
  7351. * @param v2 (Vector3) the second control point
  7352. * @param v3 (Vector3) the end point of the Cubic Bezier
  7353. * @param nbPoints (integer) the wanted number of points in the curve
  7354. */
  7355. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7356. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7357. var bez = new Array();
  7358. var equation = function (t, val0, val1, val2, val3) {
  7359. 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;
  7360. return res;
  7361. };
  7362. for (var i = 0; i <= nbPoints; i++) {
  7363. 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)));
  7364. }
  7365. return new Curve3(bez);
  7366. };
  7367. /**
  7368. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7369. * @param p1 (Vector3) the origin point of the Hermite Spline
  7370. * @param t1 (Vector3) the tangent vector at the origin point
  7371. * @param p2 (Vector3) the end point of the Hermite Spline
  7372. * @param t2 (Vector3) the tangent vector at the end point
  7373. * @param nbPoints (integer) the wanted number of points in the curve
  7374. */
  7375. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7376. var hermite = new Array();
  7377. var step = 1.0 / nbPoints;
  7378. for (var i = 0; i <= nbPoints; i++) {
  7379. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7380. }
  7381. return new Curve3(hermite);
  7382. };
  7383. /**
  7384. * Returns a Curve3 object along a CatmullRom Spline curve :
  7385. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7386. * @param nbPoints (integer) the wanted number of points between each curve control points
  7387. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7388. */
  7389. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7390. var catmullRom = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. var amount = 0.0;
  7393. if (closed) {
  7394. var pointsCount = points.length;
  7395. for (var i = 0; i < pointsCount; i++) {
  7396. amount = 0;
  7397. for (var c = 0; c < nbPoints; c++) {
  7398. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7399. amount += step;
  7400. }
  7401. }
  7402. catmullRom.push(catmullRom[0]);
  7403. }
  7404. else {
  7405. var totalPoints = new Array();
  7406. totalPoints.push(points[0].clone());
  7407. Array.prototype.push.apply(totalPoints, points);
  7408. totalPoints.push(points[points.length - 1].clone());
  7409. for (var i = 0; i < totalPoints.length - 3; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. i--;
  7417. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7418. }
  7419. return new Curve3(catmullRom);
  7420. };
  7421. /**
  7422. * Returns the Curve3 stored array of successive Vector3
  7423. */
  7424. Curve3.prototype.getPoints = function () {
  7425. return this._points;
  7426. };
  7427. /**
  7428. * Returns the computed length (float) of the curve.
  7429. */
  7430. Curve3.prototype.length = function () {
  7431. return this._length;
  7432. };
  7433. /**
  7434. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7435. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7436. * curveA and curveB keep unchanged.
  7437. */
  7438. Curve3.prototype.continue = function (curve) {
  7439. var lastPoint = this._points[this._points.length - 1];
  7440. var continuedPoints = this._points.slice();
  7441. var curvePoints = curve.getPoints();
  7442. for (var i = 1; i < curvePoints.length; i++) {
  7443. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7444. }
  7445. var continuedCurve = new Curve3(continuedPoints);
  7446. return continuedCurve;
  7447. };
  7448. Curve3.prototype._computeLength = function (path) {
  7449. var l = 0;
  7450. for (var i = 1; i < path.length; i++) {
  7451. l += (path[i].subtract(path[i - 1])).length();
  7452. }
  7453. return l;
  7454. };
  7455. return Curve3;
  7456. }());
  7457. BABYLON.Curve3 = Curve3;
  7458. // Vertex formats
  7459. var PositionNormalVertex = /** @class */ (function () {
  7460. function PositionNormalVertex(position, normal) {
  7461. if (position === void 0) { position = Vector3.Zero(); }
  7462. if (normal === void 0) { normal = Vector3.Up(); }
  7463. this.position = position;
  7464. this.normal = normal;
  7465. }
  7466. PositionNormalVertex.prototype.clone = function () {
  7467. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7468. };
  7469. return PositionNormalVertex;
  7470. }());
  7471. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7472. var PositionNormalTextureVertex = /** @class */ (function () {
  7473. function PositionNormalTextureVertex(position, normal, uv) {
  7474. if (position === void 0) { position = Vector3.Zero(); }
  7475. if (normal === void 0) { normal = Vector3.Up(); }
  7476. if (uv === void 0) { uv = Vector2.Zero(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. this.uv = uv;
  7480. }
  7481. PositionNormalTextureVertex.prototype.clone = function () {
  7482. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7483. };
  7484. return PositionNormalTextureVertex;
  7485. }());
  7486. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7487. // Temporary pre-allocated objects for engine internal use
  7488. // usage in any internal function :
  7489. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7490. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7491. var Tmp = /** @class */ (function () {
  7492. function Tmp() {
  7493. }
  7494. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7495. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7496. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7497. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7498. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7499. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7500. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7501. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7502. Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7505. return Tmp;
  7506. }());
  7507. BABYLON.Tmp = Tmp;
  7508. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7509. var MathTmp = /** @class */ (function () {
  7510. function MathTmp() {
  7511. }
  7512. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7513. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7514. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7515. return MathTmp;
  7516. }());
  7517. })(BABYLON || (BABYLON = {}));
  7518. //# sourceMappingURL=babylon.math.js.map
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. var Scalar = /** @class */ (function () {
  7522. function Scalar() {
  7523. }
  7524. /**
  7525. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7526. */
  7527. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7528. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7529. var num = a - b;
  7530. return -epsilon <= num && num <= epsilon;
  7531. };
  7532. /**
  7533. * Returns a string : the upper case translation of the number i to hexadecimal.
  7534. */
  7535. Scalar.ToHex = function (i) {
  7536. var str = i.toString(16);
  7537. if (i <= 15) {
  7538. return ("0" + str).toUpperCase();
  7539. }
  7540. return str.toUpperCase();
  7541. };
  7542. /**
  7543. * Returns -1 if value is negative and +1 is value is positive.
  7544. * Returns the value itself if it's equal to zero.
  7545. */
  7546. Scalar.Sign = function (value) {
  7547. value = +value; // convert to a number
  7548. if (value === 0 || isNaN(value))
  7549. return value;
  7550. return value > 0 ? 1 : -1;
  7551. };
  7552. /**
  7553. * Returns the value itself if it's between min and max.
  7554. * Returns min if the value is lower than min.
  7555. * Returns max if the value is greater than max.
  7556. */
  7557. Scalar.Clamp = function (value, min, max) {
  7558. if (min === void 0) { min = 0; }
  7559. if (max === void 0) { max = 1; }
  7560. return Math.min(max, Math.max(min, value));
  7561. };
  7562. /**
  7563. * Returns the log2 of value.
  7564. */
  7565. Scalar.Log2 = function (value) {
  7566. return Math.log(value) * Math.LOG2E;
  7567. };
  7568. /**
  7569. * Loops the value, so that it is never larger than length and never smaller than 0.
  7570. *
  7571. * This is similar to the modulo operator but it works with floating point numbers.
  7572. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7573. * With t = 5 and length = 2.5, the result would be 0.0.
  7574. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7575. */
  7576. Scalar.Repeat = function (value, length) {
  7577. return value - Math.floor(value / length) * length;
  7578. };
  7579. /**
  7580. * Normalize the value between 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Normalize = function (value, min, max) {
  7583. return (value - min) / (max - min);
  7584. };
  7585. /**
  7586. * Denormalize the value from 0.0 and 1.0 using min and max values
  7587. */
  7588. Scalar.Denormalize = function (normalized, min, max) {
  7589. return (normalized * (max - min) + min);
  7590. };
  7591. /**
  7592. * Calculates the shortest difference between two given angles given in degrees.
  7593. */
  7594. Scalar.DeltaAngle = function (current, target) {
  7595. var num = Scalar.Repeat(target - current, 360.0);
  7596. if (num > 180.0) {
  7597. num -= 360.0;
  7598. }
  7599. return num;
  7600. };
  7601. /**
  7602. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7603. *
  7604. * The returned value will move back and forth between 0 and length
  7605. */
  7606. Scalar.PingPong = function (tx, length) {
  7607. var t = Scalar.Repeat(tx, length * 2.0);
  7608. return length - Math.abs(t - length);
  7609. };
  7610. /**
  7611. * Interpolates between min and max with smoothing at the limits.
  7612. *
  7613. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7614. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7615. */
  7616. Scalar.SmoothStep = function (from, to, tx) {
  7617. var t = Scalar.Clamp(tx);
  7618. t = -2.0 * t * t * t + 3.0 * t * t;
  7619. return to * t + from * (1.0 - t);
  7620. };
  7621. /**
  7622. * Moves a value current towards target.
  7623. *
  7624. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7625. * Negative values of maxDelta pushes the value away from target.
  7626. */
  7627. Scalar.MoveTowards = function (current, target, maxDelta) {
  7628. var result = 0;
  7629. if (Math.abs(target - current) <= maxDelta) {
  7630. result = target;
  7631. }
  7632. else {
  7633. result = current + Scalar.Sign(target - current) * maxDelta;
  7634. }
  7635. return result;
  7636. };
  7637. /**
  7638. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7639. *
  7640. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7641. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7642. */
  7643. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7644. var num = Scalar.DeltaAngle(current, target);
  7645. var result = 0;
  7646. if (-maxDelta < num && num < maxDelta) {
  7647. result = target;
  7648. }
  7649. else {
  7650. target = current + num;
  7651. result = Scalar.MoveTowards(current, target, maxDelta);
  7652. }
  7653. return result;
  7654. };
  7655. /**
  7656. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7657. */
  7658. Scalar.Lerp = function (start, end, amount) {
  7659. return start + ((end - start) * amount);
  7660. };
  7661. /**
  7662. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7663. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7664. */
  7665. Scalar.LerpAngle = function (start, end, amount) {
  7666. var num = Scalar.Repeat(end - start, 360.0);
  7667. if (num > 180.0) {
  7668. num -= 360.0;
  7669. }
  7670. return start + num * Scalar.Clamp(amount);
  7671. };
  7672. /**
  7673. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7674. */
  7675. Scalar.InverseLerp = function (a, b, value) {
  7676. var result = 0;
  7677. if (a != b) {
  7678. result = Scalar.Clamp((value - a) / (b - a));
  7679. }
  7680. else {
  7681. result = 0.0;
  7682. }
  7683. return result;
  7684. };
  7685. /**
  7686. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7687. */
  7688. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7689. var squared = amount * amount;
  7690. var cubed = amount * squared;
  7691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7693. var part3 = (cubed - (2.0 * squared)) + amount;
  7694. var part4 = cubed - squared;
  7695. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7696. };
  7697. /**
  7698. * Returns a random float number between and min and max values
  7699. */
  7700. Scalar.RandomRange = function (min, max) {
  7701. if (min === max)
  7702. return min;
  7703. return ((Math.random() * (max - min)) + min);
  7704. };
  7705. /**
  7706. * This function returns percentage of a number in a given range.
  7707. *
  7708. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7709. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7710. */
  7711. Scalar.RangeToPercent = function (number, min, max) {
  7712. return ((number - min) / (max - min));
  7713. };
  7714. /**
  7715. * This function returns number that corresponds to the percentage in a given range.
  7716. *
  7717. * PercentToRange(0.34,0,100) will return 34.
  7718. */
  7719. Scalar.PercentToRange = function (percent, min, max) {
  7720. return ((max - min) * percent + min);
  7721. };
  7722. /**
  7723. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7724. * @param angle The angle to normalize in radian.
  7725. * @return The converted angle.
  7726. */
  7727. Scalar.NormalizeRadians = function (angle) {
  7728. // More precise but slower version kept for reference.
  7729. // angle = angle % Tools.TwoPi;
  7730. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7731. //if (angle > Math.PI) {
  7732. // angle -= Tools.TwoPi;
  7733. //}
  7734. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7735. return angle;
  7736. };
  7737. /**
  7738. * Two pi constants convenient for computation.
  7739. */
  7740. Scalar.TwoPi = Math.PI * 2;
  7741. return Scalar;
  7742. }());
  7743. BABYLON.Scalar = Scalar;
  7744. })(BABYLON || (BABYLON = {}));
  7745. //# sourceMappingURL=babylon.math.scalar.js.map
  7746. //# sourceMappingURL=babylon.mixins.js.map
  7747. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7748. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7749. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7750. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7751. //# sourceMappingURL=babylon.webgl2.js.map
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var __decoratorInitialStore = {};
  7755. var __mergedStore = {};
  7756. var _copySource = function (creationFunction, source, instanciate) {
  7757. var destination = creationFunction();
  7758. // Tags
  7759. if (BABYLON.Tags) {
  7760. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7761. }
  7762. var classStore = getMergedStore(destination);
  7763. // Properties
  7764. for (var property in classStore) {
  7765. var propertyDescriptor = classStore[property];
  7766. var sourceProperty = source[property];
  7767. var propertyType = propertyDescriptor.type;
  7768. if (sourceProperty !== undefined && sourceProperty !== null) {
  7769. switch (propertyType) {
  7770. case 0: // Value
  7771. case 6: // Mesh reference
  7772. case 11: // Camera reference
  7773. destination[property] = sourceProperty;
  7774. break;
  7775. case 1: // Texture
  7776. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7777. break;
  7778. case 2: // Color3
  7779. case 3: // FresnelParameters
  7780. case 4: // Vector2
  7781. case 5: // Vector3
  7782. case 7: // Color Curves
  7783. case 10: // Quaternion
  7784. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. }
  7787. }
  7788. }
  7789. return destination;
  7790. };
  7791. function getDirectStore(target) {
  7792. var classKey = target.getClassName();
  7793. if (!__decoratorInitialStore[classKey]) {
  7794. __decoratorInitialStore[classKey] = {};
  7795. }
  7796. return __decoratorInitialStore[classKey];
  7797. }
  7798. /**
  7799. * Return the list of properties flagged as serializable
  7800. * @param target: host object
  7801. */
  7802. function getMergedStore(target) {
  7803. var classKey = target.getClassName();
  7804. if (__mergedStore[classKey]) {
  7805. return __mergedStore[classKey];
  7806. }
  7807. __mergedStore[classKey] = {};
  7808. var store = __mergedStore[classKey];
  7809. var currentTarget = target;
  7810. var currentKey = classKey;
  7811. while (currentKey) {
  7812. var initialStore = __decoratorInitialStore[currentKey];
  7813. for (var property in initialStore) {
  7814. store[property] = initialStore[property];
  7815. }
  7816. var parent_1 = void 0;
  7817. var done = false;
  7818. do {
  7819. parent_1 = Object.getPrototypeOf(currentTarget);
  7820. if (!parent_1.getClassName) {
  7821. done = true;
  7822. break;
  7823. }
  7824. if (parent_1.getClassName() !== currentKey) {
  7825. break;
  7826. }
  7827. currentTarget = parent_1;
  7828. } while (parent_1);
  7829. if (done) {
  7830. break;
  7831. }
  7832. currentKey = parent_1.getClassName();
  7833. currentTarget = parent_1;
  7834. }
  7835. return store;
  7836. }
  7837. function generateSerializableMember(type, sourceName) {
  7838. return function (target, propertyKey) {
  7839. var classStore = getDirectStore(target);
  7840. if (!classStore[propertyKey]) {
  7841. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7842. }
  7843. };
  7844. }
  7845. function generateExpandMember(setCallback, targetKey) {
  7846. if (targetKey === void 0) { targetKey = null; }
  7847. return function (target, propertyKey) {
  7848. var key = targetKey || ("_" + propertyKey);
  7849. Object.defineProperty(target, propertyKey, {
  7850. get: function () {
  7851. return this[key];
  7852. },
  7853. set: function (value) {
  7854. if (this[key] === value) {
  7855. return;
  7856. }
  7857. this[key] = value;
  7858. target[setCallback].apply(this);
  7859. },
  7860. enumerable: true,
  7861. configurable: true
  7862. });
  7863. };
  7864. }
  7865. function expandToProperty(callback, targetKey) {
  7866. if (targetKey === void 0) { targetKey = null; }
  7867. return generateExpandMember(callback, targetKey);
  7868. }
  7869. BABYLON.expandToProperty = expandToProperty;
  7870. function serialize(sourceName) {
  7871. return generateSerializableMember(0, sourceName); // value member
  7872. }
  7873. BABYLON.serialize = serialize;
  7874. function serializeAsTexture(sourceName) {
  7875. return generateSerializableMember(1, sourceName); // texture member
  7876. }
  7877. BABYLON.serializeAsTexture = serializeAsTexture;
  7878. function serializeAsColor3(sourceName) {
  7879. return generateSerializableMember(2, sourceName); // color3 member
  7880. }
  7881. BABYLON.serializeAsColor3 = serializeAsColor3;
  7882. function serializeAsFresnelParameters(sourceName) {
  7883. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7884. }
  7885. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7886. function serializeAsVector2(sourceName) {
  7887. return generateSerializableMember(4, sourceName); // vector2 member
  7888. }
  7889. BABYLON.serializeAsVector2 = serializeAsVector2;
  7890. function serializeAsVector3(sourceName) {
  7891. return generateSerializableMember(5, sourceName); // vector3 member
  7892. }
  7893. BABYLON.serializeAsVector3 = serializeAsVector3;
  7894. function serializeAsMeshReference(sourceName) {
  7895. return generateSerializableMember(6, sourceName); // mesh reference member
  7896. }
  7897. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7898. function serializeAsColorCurves(sourceName) {
  7899. return generateSerializableMember(7, sourceName); // color curves
  7900. }
  7901. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7902. function serializeAsColor4(sourceName) {
  7903. return generateSerializableMember(8, sourceName); // color 4
  7904. }
  7905. BABYLON.serializeAsColor4 = serializeAsColor4;
  7906. function serializeAsImageProcessingConfiguration(sourceName) {
  7907. return generateSerializableMember(9, sourceName); // image processing
  7908. }
  7909. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7910. function serializeAsQuaternion(sourceName) {
  7911. return generateSerializableMember(10, sourceName); // quaternion member
  7912. }
  7913. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7914. /**
  7915. * Decorator used to define property that can be serialized as reference to a camera
  7916. * @param sourceName defines the name of the property to decorate
  7917. */
  7918. function serializeAsCameraReference(sourceName) {
  7919. return generateSerializableMember(11, sourceName); // camera reference member
  7920. }
  7921. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7922. var SerializationHelper = /** @class */ (function () {
  7923. function SerializationHelper() {
  7924. }
  7925. SerializationHelper.Serialize = function (entity, serializationObject) {
  7926. if (!serializationObject) {
  7927. serializationObject = {};
  7928. }
  7929. // Tags
  7930. if (BABYLON.Tags) {
  7931. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7932. }
  7933. var serializedProperties = getMergedStore(entity);
  7934. // Properties
  7935. for (var property in serializedProperties) {
  7936. var propertyDescriptor = serializedProperties[property];
  7937. var targetPropertyName = propertyDescriptor.sourceName || property;
  7938. var propertyType = propertyDescriptor.type;
  7939. var sourceProperty = entity[property];
  7940. if (sourceProperty !== undefined && sourceProperty !== null) {
  7941. switch (propertyType) {
  7942. case 0: // Value
  7943. serializationObject[targetPropertyName] = sourceProperty;
  7944. break;
  7945. case 1: // Texture
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 2: // Color3
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 3: // FresnelParameters
  7952. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7953. break;
  7954. case 4: // Vector2
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 5: // Vector3
  7958. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7959. break;
  7960. case 6: // Mesh reference
  7961. serializationObject[targetPropertyName] = sourceProperty.id;
  7962. break;
  7963. case 7: // Color Curves
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 8: // Color 4
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 9: // Image Processing
  7970. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7971. break;
  7972. case 10: // Quaternion
  7973. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7974. break;
  7975. case 11: // Camera reference
  7976. serializationObject[targetPropertyName] = sourceProperty.id;
  7977. break;
  7978. }
  7979. }
  7980. }
  7981. return serializationObject;
  7982. };
  7983. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7984. if (rootUrl === void 0) { rootUrl = null; }
  7985. var destination = creationFunction();
  7986. if (!rootUrl) {
  7987. rootUrl = "";
  7988. }
  7989. // Tags
  7990. if (BABYLON.Tags) {
  7991. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7992. }
  7993. var classStore = getMergedStore(destination);
  7994. // Properties
  7995. for (var property in classStore) {
  7996. var propertyDescriptor = classStore[property];
  7997. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7998. var propertyType = propertyDescriptor.type;
  7999. if (sourceProperty !== undefined && sourceProperty !== null) {
  8000. var dest = destination;
  8001. switch (propertyType) {
  8002. case 0: // Value
  8003. dest[property] = sourceProperty;
  8004. break;
  8005. case 1: // Texture
  8006. if (scene) {
  8007. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8008. }
  8009. break;
  8010. case 2: // Color3
  8011. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8012. break;
  8013. case 3: // FresnelParameters
  8014. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8015. break;
  8016. case 4: // Vector2
  8017. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8018. break;
  8019. case 5: // Vector3
  8020. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8021. break;
  8022. case 6: // Mesh reference
  8023. if (scene) {
  8024. dest[property] = scene.getLastMeshByID(sourceProperty);
  8025. }
  8026. break;
  8027. case 7: // Color Curves
  8028. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8029. break;
  8030. case 8: // Color 4
  8031. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8032. break;
  8033. case 9: // Image Processing
  8034. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8035. break;
  8036. case 10: // Quaternion
  8037. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8038. break;
  8039. case 11: // Camera reference
  8040. if (scene) {
  8041. dest[property] = scene.getCameraByID(sourceProperty);
  8042. }
  8043. break;
  8044. }
  8045. }
  8046. }
  8047. return destination;
  8048. };
  8049. SerializationHelper.Clone = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, false);
  8051. };
  8052. SerializationHelper.Instanciate = function (creationFunction, source) {
  8053. return _copySource(creationFunction, source, true);
  8054. };
  8055. return SerializationHelper;
  8056. }());
  8057. BABYLON.SerializationHelper = SerializationHelper;
  8058. })(BABYLON || (BABYLON = {}));
  8059. //# sourceMappingURL=babylon.decorators.js.map
  8060. var BABYLON;
  8061. (function (BABYLON) {
  8062. /**
  8063. * Wrapper class for promise with external resolve and reject.
  8064. */
  8065. var Deferred = /** @class */ (function () {
  8066. /**
  8067. * Constructor for this deferred object.
  8068. */
  8069. function Deferred() {
  8070. var _this = this;
  8071. this.promise = new Promise(function (resolve, reject) {
  8072. _this._resolve = resolve;
  8073. _this._reject = reject;
  8074. });
  8075. }
  8076. Object.defineProperty(Deferred.prototype, "resolve", {
  8077. /**
  8078. * The resolve method of the promise associated with this deferred object.
  8079. */
  8080. get: function () {
  8081. return this._resolve;
  8082. },
  8083. enumerable: true,
  8084. configurable: true
  8085. });
  8086. Object.defineProperty(Deferred.prototype, "reject", {
  8087. /**
  8088. * The reject method of the promise associated with this deferred object.
  8089. */
  8090. get: function () {
  8091. return this._reject;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. return Deferred;
  8097. }());
  8098. BABYLON.Deferred = Deferred;
  8099. })(BABYLON || (BABYLON = {}));
  8100. //# sourceMappingURL=babylon.deferred.js.map
  8101. var BABYLON;
  8102. (function (BABYLON) {
  8103. /**
  8104. * A class serves as a medium between the observable and its observers
  8105. */
  8106. var EventState = /** @class */ (function () {
  8107. /**
  8108. * Create a new EventState
  8109. * @param mask defines the mask associated with this state
  8110. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8111. * @param target defines the original target of the state
  8112. * @param currentTarget defines the current target of the state
  8113. */
  8114. function EventState(mask, skipNextObservers, target, currentTarget) {
  8115. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8116. this.initalize(mask, skipNextObservers, target, currentTarget);
  8117. }
  8118. /**
  8119. * Initialize the current event state
  8120. * @param mask defines the mask associated with this state
  8121. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8122. * @param target defines the original target of the state
  8123. * @param currentTarget defines the current target of the state
  8124. * @returns the current event state
  8125. */
  8126. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8127. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8128. this.mask = mask;
  8129. this.skipNextObservers = skipNextObservers;
  8130. this.target = target;
  8131. this.currentTarget = currentTarget;
  8132. return this;
  8133. };
  8134. return EventState;
  8135. }());
  8136. BABYLON.EventState = EventState;
  8137. /**
  8138. * Represent an Observer registered to a given Observable object.
  8139. */
  8140. var Observer = /** @class */ (function () {
  8141. /**
  8142. * Creates a new observer
  8143. * @param callback defines the callback to call when the observer is notified
  8144. * @param mask defines the mask of the observer (used to filter notifications)
  8145. * @param scope defines the current scope used to restore the JS context
  8146. */
  8147. function Observer(
  8148. /**
  8149. * Defines the callback to call when the observer is notified
  8150. */
  8151. callback,
  8152. /**
  8153. * Defines the mask of the observer (used to filter notifications)
  8154. */
  8155. mask,
  8156. /**
  8157. * Defines the current scope used to restore the JS context
  8158. */
  8159. scope) {
  8160. if (scope === void 0) { scope = null; }
  8161. this.callback = callback;
  8162. this.mask = mask;
  8163. this.scope = scope;
  8164. /** @hidden */
  8165. this._willBeUnregistered = false;
  8166. /**
  8167. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8168. */
  8169. this.unregisterOnNextCall = false;
  8170. }
  8171. return Observer;
  8172. }());
  8173. BABYLON.Observer = Observer;
  8174. /**
  8175. * Represent a list of observers registered to multiple Observables object.
  8176. */
  8177. var MultiObserver = /** @class */ (function () {
  8178. function MultiObserver() {
  8179. }
  8180. /**
  8181. * Release associated resources
  8182. */
  8183. MultiObserver.prototype.dispose = function () {
  8184. if (this._observers && this._observables) {
  8185. for (var index = 0; index < this._observers.length; index++) {
  8186. this._observables[index].remove(this._observers[index]);
  8187. }
  8188. }
  8189. this._observers = null;
  8190. this._observables = null;
  8191. };
  8192. /**
  8193. * Raise a callback when one of the observable will notify
  8194. * @param observables defines a list of observables to watch
  8195. * @param callback defines the callback to call on notification
  8196. * @param mask defines the mask used to filter notifications
  8197. * @param scope defines the current scope used to restore the JS context
  8198. * @returns the new MultiObserver
  8199. */
  8200. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8201. if (mask === void 0) { mask = -1; }
  8202. if (scope === void 0) { scope = null; }
  8203. var result = new MultiObserver();
  8204. result._observers = new Array();
  8205. result._observables = observables;
  8206. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8207. var observable = observables_1[_i];
  8208. var observer = observable.add(callback, mask, false, scope);
  8209. if (observer) {
  8210. result._observers.push(observer);
  8211. }
  8212. }
  8213. return result;
  8214. };
  8215. return MultiObserver;
  8216. }());
  8217. BABYLON.MultiObserver = MultiObserver;
  8218. /**
  8219. * The Observable class is a simple implementation of the Observable pattern.
  8220. *
  8221. * 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.
  8222. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8223. * 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).
  8224. * 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.
  8225. */
  8226. var Observable = /** @class */ (function () {
  8227. /**
  8228. * Creates a new observable
  8229. * @param onObserverAdded defines a callback to call when a new observer is added
  8230. */
  8231. function Observable(onObserverAdded) {
  8232. this._observers = new Array();
  8233. this._eventState = new EventState(0);
  8234. if (onObserverAdded) {
  8235. this._onObserverAdded = onObserverAdded;
  8236. }
  8237. }
  8238. /**
  8239. * Create a new Observer with the specified callback
  8240. * @param callback the callback that will be executed for that Observer
  8241. * @param mask the mask used to filter observers
  8242. * @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.
  8243. * @param scope optional scope for the callback to be called from
  8244. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8245. * @returns the new observer created for the callback
  8246. */
  8247. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8248. if (mask === void 0) { mask = -1; }
  8249. if (insertFirst === void 0) { insertFirst = false; }
  8250. if (scope === void 0) { scope = null; }
  8251. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8252. if (!callback) {
  8253. return null;
  8254. }
  8255. var observer = new Observer(callback, mask, scope);
  8256. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8257. if (insertFirst) {
  8258. this._observers.unshift(observer);
  8259. }
  8260. else {
  8261. this._observers.push(observer);
  8262. }
  8263. if (this._onObserverAdded) {
  8264. this._onObserverAdded(observer);
  8265. }
  8266. return observer;
  8267. };
  8268. /**
  8269. * Create a new Observer with the specified callback and unregisters after the next notification
  8270. * @param callback the callback that will be executed for that Observer
  8271. * @returns the new observer created for the callback
  8272. */
  8273. Observable.prototype.addOnce = function (callback) {
  8274. return this.add(callback, undefined, undefined, undefined, true);
  8275. };
  8276. /**
  8277. * Remove an Observer from the Observable object
  8278. * @param observer the instance of the Observer to remove
  8279. * @returns false if it doesn't belong to this Observable
  8280. */
  8281. Observable.prototype.remove = function (observer) {
  8282. if (!observer) {
  8283. return false;
  8284. }
  8285. var index = this._observers.indexOf(observer);
  8286. if (index !== -1) {
  8287. this._deferUnregister(observer);
  8288. return true;
  8289. }
  8290. return false;
  8291. };
  8292. /**
  8293. * Remove a callback from the Observable object
  8294. * @param callback the callback to remove
  8295. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8296. * @returns false if it doesn't belong to this Observable
  8297. */
  8298. Observable.prototype.removeCallback = function (callback, scope) {
  8299. for (var index = 0; index < this._observers.length; index++) {
  8300. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8301. this._deferUnregister(this._observers[index]);
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. };
  8307. Observable.prototype._deferUnregister = function (observer) {
  8308. var _this = this;
  8309. observer.unregisterOnNextCall = false;
  8310. observer._willBeUnregistered = true;
  8311. BABYLON.Tools.SetImmediate(function () {
  8312. _this._remove(observer);
  8313. });
  8314. };
  8315. // This should only be called when not iterating over _observers to avoid callback skipping.
  8316. // Removes an observer from the _observer Array.
  8317. Observable.prototype._remove = function (observer) {
  8318. if (!observer) {
  8319. return false;
  8320. }
  8321. var index = this._observers.indexOf(observer);
  8322. if (index !== -1) {
  8323. this._observers.splice(index, 1);
  8324. return true;
  8325. }
  8326. return false;
  8327. };
  8328. /**
  8329. * Notify all Observers by calling their respective callback with the given data
  8330. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8331. * @param eventData defines the data to send to all observers
  8332. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8333. * @param target defines the original target of the state
  8334. * @param currentTarget defines the current target of the state
  8335. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8336. */
  8337. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (!this._observers.length) {
  8340. return true;
  8341. }
  8342. var state = this._eventState;
  8343. state.mask = mask;
  8344. state.target = target;
  8345. state.currentTarget = currentTarget;
  8346. state.skipNextObservers = false;
  8347. state.lastReturnValue = eventData;
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs._willBeUnregistered) {
  8351. continue;
  8352. }
  8353. if (obs.mask & mask) {
  8354. if (obs.scope) {
  8355. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8356. }
  8357. else {
  8358. state.lastReturnValue = obs.callback(eventData, state);
  8359. }
  8360. if (obs.unregisterOnNextCall) {
  8361. this._deferUnregister(obs);
  8362. }
  8363. }
  8364. if (state.skipNextObservers) {
  8365. return false;
  8366. }
  8367. }
  8368. return true;
  8369. };
  8370. /**
  8371. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8372. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8373. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8374. * and it is crucial that all callbacks will be executed.
  8375. * The order of the callbacks is kept, callbacks are not executed parallel.
  8376. *
  8377. * @param eventData The data to be sent to each callback
  8378. * @param mask is used to filter observers defaults to -1
  8379. * @param target defines the callback target (see EventState)
  8380. * @param currentTarget defines he current object in the bubbling phase
  8381. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8382. */
  8383. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8384. var _this = this;
  8385. if (mask === void 0) { mask = -1; }
  8386. // create an empty promise
  8387. var p = Promise.resolve(eventData);
  8388. // no observers? return this promise.
  8389. if (!this._observers.length) {
  8390. return p;
  8391. }
  8392. var state = this._eventState;
  8393. state.mask = mask;
  8394. state.target = target;
  8395. state.currentTarget = currentTarget;
  8396. state.skipNextObservers = false;
  8397. // execute one callback after another (not using Promise.all, the order is important)
  8398. this._observers.forEach(function (obs) {
  8399. if (state.skipNextObservers) {
  8400. return;
  8401. }
  8402. if (obs._willBeUnregistered) {
  8403. return;
  8404. }
  8405. if (obs.mask & mask) {
  8406. if (obs.scope) {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback.apply(obs.scope, [eventData, state]);
  8410. });
  8411. }
  8412. else {
  8413. p = p.then(function (lastReturnedValue) {
  8414. state.lastReturnValue = lastReturnedValue;
  8415. return obs.callback(eventData, state);
  8416. });
  8417. }
  8418. if (obs.unregisterOnNextCall) {
  8419. _this._deferUnregister(obs);
  8420. }
  8421. }
  8422. });
  8423. // return the eventData
  8424. return p.then(function () { return eventData; });
  8425. };
  8426. /**
  8427. * Notify a specific observer
  8428. * @param observer defines the observer to notify
  8429. * @param eventData defines the data to be sent to each callback
  8430. * @param mask is used to filter observers defaults to -1
  8431. */
  8432. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8433. if (mask === void 0) { mask = -1; }
  8434. var state = this._eventState;
  8435. state.mask = mask;
  8436. state.skipNextObservers = false;
  8437. observer.callback(eventData, state);
  8438. };
  8439. /**
  8440. * Gets a boolean indicating if the observable has at least one observer
  8441. * @returns true is the Observable has at least one Observer registered
  8442. */
  8443. Observable.prototype.hasObservers = function () {
  8444. return this._observers.length > 0;
  8445. };
  8446. /**
  8447. * Clear the list of observers
  8448. */
  8449. Observable.prototype.clear = function () {
  8450. this._observers = new Array();
  8451. this._onObserverAdded = null;
  8452. };
  8453. /**
  8454. * Clone the current observable
  8455. * @returns a new observable
  8456. */
  8457. Observable.prototype.clone = function () {
  8458. var result = new Observable();
  8459. result._observers = this._observers.slice(0);
  8460. return result;
  8461. };
  8462. /**
  8463. * Does this observable handles observer registered with a given mask
  8464. * @param mask defines the mask to be tested
  8465. * @return whether or not one observer registered with the given mask is handeled
  8466. **/
  8467. Observable.prototype.hasSpecificMask = function (mask) {
  8468. if (mask === void 0) { mask = -1; }
  8469. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8470. var obs = _a[_i];
  8471. if (obs.mask & mask || obs.mask === mask) {
  8472. return true;
  8473. }
  8474. }
  8475. return false;
  8476. };
  8477. return Observable;
  8478. }());
  8479. BABYLON.Observable = Observable;
  8480. })(BABYLON || (BABYLON = {}));
  8481. //# sourceMappingURL=babylon.observable.js.map
  8482. var BABYLON;
  8483. (function (BABYLON) {
  8484. var SmartArray = /** @class */ (function () {
  8485. function SmartArray(capacity) {
  8486. this.length = 0;
  8487. this.data = new Array(capacity);
  8488. this._id = SmartArray._GlobalId++;
  8489. }
  8490. SmartArray.prototype.push = function (value) {
  8491. this.data[this.length++] = value;
  8492. if (this.length > this.data.length) {
  8493. this.data.length *= 2;
  8494. }
  8495. };
  8496. SmartArray.prototype.forEach = function (func) {
  8497. for (var index = 0; index < this.length; index++) {
  8498. func(this.data[index]);
  8499. }
  8500. };
  8501. SmartArray.prototype.sort = function (compareFn) {
  8502. this.data.sort(compareFn);
  8503. };
  8504. SmartArray.prototype.reset = function () {
  8505. this.length = 0;
  8506. };
  8507. SmartArray.prototype.dispose = function () {
  8508. this.reset();
  8509. if (this.data) {
  8510. this.data.length = 0;
  8511. this.data = [];
  8512. }
  8513. };
  8514. SmartArray.prototype.concat = function (array) {
  8515. if (array.length === 0) {
  8516. return;
  8517. }
  8518. if (this.length + array.length > this.data.length) {
  8519. this.data.length = (this.length + array.length) * 2;
  8520. }
  8521. for (var index = 0; index < array.length; index++) {
  8522. this.data[this.length++] = (array.data || array)[index];
  8523. }
  8524. };
  8525. SmartArray.prototype.indexOf = function (value) {
  8526. var position = this.data.indexOf(value);
  8527. if (position >= this.length) {
  8528. return -1;
  8529. }
  8530. return position;
  8531. };
  8532. SmartArray.prototype.contains = function (value) {
  8533. return this.data.indexOf(value) !== -1;
  8534. };
  8535. // Statics
  8536. SmartArray._GlobalId = 0;
  8537. return SmartArray;
  8538. }());
  8539. BABYLON.SmartArray = SmartArray;
  8540. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8541. __extends(SmartArrayNoDuplicate, _super);
  8542. function SmartArrayNoDuplicate() {
  8543. var _this = _super !== null && _super.apply(this, arguments) || this;
  8544. _this._duplicateId = 0;
  8545. return _this;
  8546. }
  8547. SmartArrayNoDuplicate.prototype.push = function (value) {
  8548. _super.prototype.push.call(this, value);
  8549. if (!value.__smartArrayFlags) {
  8550. value.__smartArrayFlags = {};
  8551. }
  8552. value.__smartArrayFlags[this._id] = this._duplicateId;
  8553. };
  8554. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8555. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8556. return false;
  8557. }
  8558. this.push(value);
  8559. return true;
  8560. };
  8561. SmartArrayNoDuplicate.prototype.reset = function () {
  8562. _super.prototype.reset.call(this);
  8563. this._duplicateId++;
  8564. };
  8565. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8566. if (array.length === 0) {
  8567. return;
  8568. }
  8569. if (this.length + array.length > this.data.length) {
  8570. this.data.length = (this.length + array.length) * 2;
  8571. }
  8572. for (var index = 0; index < array.length; index++) {
  8573. var item = (array.data || array)[index];
  8574. this.pushNoDuplicate(item);
  8575. }
  8576. };
  8577. return SmartArrayNoDuplicate;
  8578. }(SmartArray));
  8579. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8580. })(BABYLON || (BABYLON = {}));
  8581. //# sourceMappingURL=babylon.smartArray.js.map
  8582. var BABYLON;
  8583. (function (BABYLON) {
  8584. /** Class used to store color gradient */
  8585. var ColorGradient = /** @class */ (function () {
  8586. function ColorGradient() {
  8587. }
  8588. /**
  8589. * Will get a color picked randomly between color1 and color2.
  8590. * If color2 is undefined then color1 will be used
  8591. * @param result defines the target Color4 to store the result in
  8592. */
  8593. ColorGradient.prototype.getColorToRef = function (result) {
  8594. if (!this.color2) {
  8595. result.copyFrom(this.color1);
  8596. return;
  8597. }
  8598. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8599. };
  8600. return ColorGradient;
  8601. }());
  8602. BABYLON.ColorGradient = ColorGradient;
  8603. /** Class used to store factor gradient */
  8604. var FactorGradient = /** @class */ (function () {
  8605. function FactorGradient() {
  8606. }
  8607. /**
  8608. * Will get a number picked randomly between factor1 and factor2.
  8609. * If factor2 is undefined then factor1 will be used
  8610. * @returns the picked number
  8611. */
  8612. FactorGradient.prototype.getFactor = function () {
  8613. if (this.factor2 === undefined) {
  8614. return this.factor1;
  8615. }
  8616. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8617. };
  8618. return FactorGradient;
  8619. }());
  8620. BABYLON.FactorGradient = FactorGradient;
  8621. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8622. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8623. var LoadFileError = /** @class */ (function (_super) {
  8624. __extends(LoadFileError, _super);
  8625. function LoadFileError(message, request) {
  8626. var _this = _super.call(this, message) || this;
  8627. _this.request = request;
  8628. _this.name = "LoadFileError";
  8629. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8630. return _this;
  8631. }
  8632. // Polyfill for Object.setPrototypeOf if necessary.
  8633. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8634. return LoadFileError;
  8635. }(Error));
  8636. BABYLON.LoadFileError = LoadFileError;
  8637. var RetryStrategy = /** @class */ (function () {
  8638. function RetryStrategy() {
  8639. }
  8640. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8641. if (maxRetries === void 0) { maxRetries = 3; }
  8642. if (baseInterval === void 0) { baseInterval = 500; }
  8643. return function (url, request, retryIndex) {
  8644. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8645. return -1;
  8646. }
  8647. return Math.pow(2, retryIndex) * baseInterval;
  8648. };
  8649. };
  8650. return RetryStrategy;
  8651. }());
  8652. BABYLON.RetryStrategy = RetryStrategy;
  8653. // Screenshots
  8654. var screenshotCanvas;
  8655. var cloneValue = function (source, destinationObject) {
  8656. if (!source)
  8657. return null;
  8658. if (source instanceof BABYLON.Mesh) {
  8659. return null;
  8660. }
  8661. if (source instanceof BABYLON.SubMesh) {
  8662. return source.clone(destinationObject);
  8663. }
  8664. else if (source.clone) {
  8665. return source.clone();
  8666. }
  8667. return null;
  8668. };
  8669. var Tools = /** @class */ (function () {
  8670. function Tools() {
  8671. }
  8672. /**
  8673. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8674. * @param u defines the coordinate on X axis
  8675. * @param v defines the coordinate on Y axis
  8676. * @param width defines the width of the source data
  8677. * @param height defines the height of the source data
  8678. * @param pixels defines the source byte array
  8679. * @param color defines the output color
  8680. */
  8681. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8682. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8683. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8684. var position = (wrappedU + wrappedV * width) * 4;
  8685. color.r = pixels[position] / 255;
  8686. color.g = pixels[position + 1] / 255;
  8687. color.b = pixels[position + 2] / 255;
  8688. color.a = pixels[position + 3] / 255;
  8689. };
  8690. /**
  8691. * Interpolates between a and b via alpha
  8692. * @param a The lower value (returned when alpha = 0)
  8693. * @param b The upper value (returned when alpha = 1)
  8694. * @param alpha The interpolation-factor
  8695. * @return The mixed value
  8696. */
  8697. Tools.Mix = function (a, b, alpha) {
  8698. return a * (1 - alpha) + b * alpha;
  8699. };
  8700. Tools.Instantiate = function (className) {
  8701. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8702. return Tools.RegisteredExternalClasses[className];
  8703. }
  8704. var arr = className.split(".");
  8705. var fn = (window || this);
  8706. for (var i = 0, len = arr.length; i < len; i++) {
  8707. fn = fn[arr[i]];
  8708. }
  8709. if (typeof fn !== "function") {
  8710. return null;
  8711. }
  8712. return fn;
  8713. };
  8714. /**
  8715. * Provides a slice function that will work even on IE
  8716. * @param data defines the array to slice
  8717. * @param start defines the start of the data (optional)
  8718. * @param end defines the end of the data (optional)
  8719. * @returns the new sliced array
  8720. */
  8721. Tools.Slice = function (data, start, end) {
  8722. if (data.slice) {
  8723. return data.slice(start, end);
  8724. }
  8725. return Array.prototype.slice.call(data, start, end);
  8726. };
  8727. Tools.SetImmediate = function (action) {
  8728. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8729. window.setImmediate(action);
  8730. }
  8731. else {
  8732. setTimeout(action, 1);
  8733. }
  8734. };
  8735. Tools.IsExponentOfTwo = function (value) {
  8736. var count = 1;
  8737. do {
  8738. count *= 2;
  8739. } while (count < value);
  8740. return count === value;
  8741. };
  8742. /**
  8743. * Returns the nearest 32-bit single precision float representation of a Number
  8744. * @param value A Number. If the parameter is of a different type, it will get converted
  8745. * to a number or to NaN if it cannot be converted
  8746. * @returns number
  8747. */
  8748. Tools.FloatRound = function (value) {
  8749. if (Math.fround) {
  8750. return Math.fround(value);
  8751. }
  8752. return (Tools._tmpFloatArray[0] = value);
  8753. };
  8754. /**
  8755. * Find the next highest power of two.
  8756. * @param x Number to start search from.
  8757. * @return Next highest power of two.
  8758. */
  8759. Tools.CeilingPOT = function (x) {
  8760. x--;
  8761. x |= x >> 1;
  8762. x |= x >> 2;
  8763. x |= x >> 4;
  8764. x |= x >> 8;
  8765. x |= x >> 16;
  8766. x++;
  8767. return x;
  8768. };
  8769. /**
  8770. * Find the next lowest power of two.
  8771. * @param x Number to start search from.
  8772. * @return Next lowest power of two.
  8773. */
  8774. Tools.FloorPOT = function (x) {
  8775. x = x | (x >> 1);
  8776. x = x | (x >> 2);
  8777. x = x | (x >> 4);
  8778. x = x | (x >> 8);
  8779. x = x | (x >> 16);
  8780. return x - (x >> 1);
  8781. };
  8782. /**
  8783. * Find the nearest power of two.
  8784. * @param x Number to start search from.
  8785. * @return Next nearest power of two.
  8786. */
  8787. Tools.NearestPOT = function (x) {
  8788. var c = Tools.CeilingPOT(x);
  8789. var f = Tools.FloorPOT(x);
  8790. return (c - x) > (x - f) ? f : c;
  8791. };
  8792. Tools.GetExponentOfTwo = function (value, max, mode) {
  8793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8794. var pot;
  8795. switch (mode) {
  8796. case BABYLON.Engine.SCALEMODE_FLOOR:
  8797. pot = Tools.FloorPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_NEAREST:
  8800. pot = Tools.NearestPOT(value);
  8801. break;
  8802. case BABYLON.Engine.SCALEMODE_CEILING:
  8803. default:
  8804. pot = Tools.CeilingPOT(value);
  8805. break;
  8806. }
  8807. return Math.min(pot, max);
  8808. };
  8809. Tools.GetFilename = function (path) {
  8810. var index = path.lastIndexOf("/");
  8811. if (index < 0)
  8812. return path;
  8813. return path.substring(index + 1);
  8814. };
  8815. /**
  8816. * Extracts the "folder" part of a path (everything before the filename).
  8817. * @param uri The URI to extract the info from
  8818. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8819. * @returns The "folder" part of the path
  8820. */
  8821. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8822. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8823. var index = uri.lastIndexOf("/");
  8824. if (index < 0) {
  8825. if (returnUnchangedIfNoSlash) {
  8826. return uri;
  8827. }
  8828. return "";
  8829. }
  8830. return uri.substring(0, index + 1);
  8831. };
  8832. Tools.GetDOMTextContent = function (element) {
  8833. var result = "";
  8834. var child = element.firstChild;
  8835. while (child) {
  8836. if (child.nodeType === 3) {
  8837. result += child.textContent;
  8838. }
  8839. child = child.nextSibling;
  8840. }
  8841. return result;
  8842. };
  8843. Tools.ToDegrees = function (angle) {
  8844. return angle * 180 / Math.PI;
  8845. };
  8846. Tools.ToRadians = function (angle) {
  8847. return angle * Math.PI / 180;
  8848. };
  8849. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8850. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8851. var output = "";
  8852. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8853. var i = 0;
  8854. var bytes = new Uint8Array(buffer);
  8855. while (i < bytes.length) {
  8856. chr1 = bytes[i++];
  8857. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8858. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8859. enc1 = chr1 >> 2;
  8860. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8861. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8862. enc4 = chr3 & 63;
  8863. if (isNaN(chr2)) {
  8864. enc3 = enc4 = 64;
  8865. }
  8866. else if (isNaN(chr3)) {
  8867. enc4 = 64;
  8868. }
  8869. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8870. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8871. }
  8872. return "data:image/png;base64," + output;
  8873. };
  8874. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8875. if (bias === void 0) { bias = null; }
  8876. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8877. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8878. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8879. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8880. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8881. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8882. }
  8883. if (bias) {
  8884. minimum.x -= minimum.x * bias.x + bias.y;
  8885. minimum.y -= minimum.y * bias.x + bias.y;
  8886. minimum.z -= minimum.z * bias.x + bias.y;
  8887. maximum.x += maximum.x * bias.x + bias.y;
  8888. maximum.y += maximum.y * bias.x + bias.y;
  8889. maximum.z += maximum.z * bias.x + bias.y;
  8890. }
  8891. return {
  8892. minimum: minimum,
  8893. maximum: maximum
  8894. };
  8895. };
  8896. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8897. if (bias === void 0) { bias = null; }
  8898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8900. if (!stride) {
  8901. stride = 3;
  8902. }
  8903. for (var index = start; index < start + count; index++) {
  8904. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8907. }
  8908. if (bias) {
  8909. minimum.x -= minimum.x * bias.x + bias.y;
  8910. minimum.y -= minimum.y * bias.x + bias.y;
  8911. minimum.z -= minimum.z * bias.x + bias.y;
  8912. maximum.x += maximum.x * bias.x + bias.y;
  8913. maximum.y += maximum.y * bias.x + bias.y;
  8914. maximum.z += maximum.z * bias.x + bias.y;
  8915. }
  8916. return {
  8917. minimum: minimum,
  8918. maximum: maximum
  8919. };
  8920. };
  8921. Tools.Vector2ArrayFeeder = function (array) {
  8922. return function (index) {
  8923. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8924. var length = isFloatArray ? array.length / 2 : array.length;
  8925. if (index >= length) {
  8926. return null;
  8927. }
  8928. if (isFloatArray) {
  8929. var fa = array;
  8930. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8931. }
  8932. var a = array;
  8933. return a[index];
  8934. };
  8935. };
  8936. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8937. if (bias === void 0) { bias = null; }
  8938. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8939. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8940. var i = 0;
  8941. var cur = feeder(i++);
  8942. while (cur) {
  8943. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8944. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8945. cur = feeder(i++);
  8946. }
  8947. if (bias) {
  8948. minimum.x -= minimum.x * bias.x + bias.y;
  8949. minimum.y -= minimum.y * bias.x + bias.y;
  8950. maximum.x += maximum.x * bias.x + bias.y;
  8951. maximum.y += maximum.y * bias.x + bias.y;
  8952. }
  8953. return {
  8954. minimum: minimum,
  8955. maximum: maximum
  8956. };
  8957. };
  8958. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8959. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8960. return null;
  8961. return Array.isArray(obj) ? obj : [obj];
  8962. };
  8963. // Misc.
  8964. Tools.GetPointerPrefix = function () {
  8965. var eventPrefix = "pointer";
  8966. // Check if pointer events are supported
  8967. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8968. eventPrefix = "mouse";
  8969. }
  8970. return eventPrefix;
  8971. };
  8972. /**
  8973. * @param func - the function to be called
  8974. * @param requester - the object that will request the next frame. Falls back to window.
  8975. */
  8976. Tools.QueueNewFrame = function (func, requester) {
  8977. if (!Tools.IsWindowObjectExist()) {
  8978. return setTimeout(func, 16);
  8979. }
  8980. if (!requester) {
  8981. requester = window;
  8982. }
  8983. if (requester.requestAnimationFrame) {
  8984. return requester.requestAnimationFrame(func);
  8985. }
  8986. else if (requester.msRequestAnimationFrame) {
  8987. return requester.msRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.webkitRequestAnimationFrame) {
  8990. return requester.webkitRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.mozRequestAnimationFrame) {
  8993. return requester.mozRequestAnimationFrame(func);
  8994. }
  8995. else if (requester.oRequestAnimationFrame) {
  8996. return requester.oRequestAnimationFrame(func);
  8997. }
  8998. else {
  8999. return window.setTimeout(func, 16);
  9000. }
  9001. };
  9002. Tools.RequestFullscreen = function (element) {
  9003. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9004. if (!requestFunction)
  9005. return;
  9006. requestFunction.call(element);
  9007. };
  9008. Tools.ExitFullscreen = function () {
  9009. if (document.exitFullscreen) {
  9010. document.exitFullscreen();
  9011. }
  9012. else if (document.mozCancelFullScreen) {
  9013. document.mozCancelFullScreen();
  9014. }
  9015. else if (document.webkitCancelFullScreen) {
  9016. document.webkitCancelFullScreen();
  9017. }
  9018. else if (document.msCancelFullScreen) {
  9019. document.msCancelFullScreen();
  9020. }
  9021. };
  9022. Tools.SetCorsBehavior = function (url, element) {
  9023. if (url && url.indexOf("data:") === 0) {
  9024. return;
  9025. }
  9026. if (Tools.CorsBehavior) {
  9027. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9028. element.crossOrigin = Tools.CorsBehavior;
  9029. }
  9030. else {
  9031. var result = Tools.CorsBehavior(url);
  9032. if (result) {
  9033. element.crossOrigin = result;
  9034. }
  9035. }
  9036. }
  9037. };
  9038. // External files
  9039. Tools.CleanUrl = function (url) {
  9040. url = url.replace(/#/mg, "%23");
  9041. return url;
  9042. };
  9043. /**
  9044. * Loads an image as an HTMLImageElement.
  9045. * @param input url string, ArrayBuffer, or Blob to load
  9046. * @param onLoad callback called when the image successfully loads
  9047. * @param onError callback called when the image fails to load
  9048. * @param database database for caching
  9049. * @returns the HTMLImageElement of the loaded image
  9050. */
  9051. Tools.LoadImage = function (input, onLoad, onError, database) {
  9052. var url;
  9053. var usingObjectURL = false;
  9054. if (input instanceof ArrayBuffer) {
  9055. url = URL.createObjectURL(new Blob([input]));
  9056. usingObjectURL = true;
  9057. }
  9058. else if (input instanceof Blob) {
  9059. url = URL.createObjectURL(input);
  9060. usingObjectURL = true;
  9061. }
  9062. else {
  9063. url = Tools.CleanUrl(input);
  9064. url = Tools.PreprocessUrl(input);
  9065. }
  9066. var img = new Image();
  9067. Tools.SetCorsBehavior(url, img);
  9068. var loadHandler = function () {
  9069. if (usingObjectURL && img.src) {
  9070. URL.revokeObjectURL(img.src);
  9071. }
  9072. img.removeEventListener("load", loadHandler);
  9073. img.removeEventListener("error", errorHandler);
  9074. onLoad(img);
  9075. };
  9076. var errorHandler = function (err) {
  9077. if (usingObjectURL && img.src) {
  9078. URL.revokeObjectURL(img.src);
  9079. }
  9080. img.removeEventListener("load", loadHandler);
  9081. img.removeEventListener("error", errorHandler);
  9082. Tools.Error("Error while trying to load image: " + input);
  9083. if (onError) {
  9084. onError("Error while trying to load image: " + input, err);
  9085. }
  9086. };
  9087. img.addEventListener("load", loadHandler);
  9088. img.addEventListener("error", errorHandler);
  9089. var noIndexedDB = function () {
  9090. img.src = url;
  9091. };
  9092. var loadFromIndexedDB = function () {
  9093. if (database) {
  9094. database.loadImageFromDB(url, img);
  9095. }
  9096. };
  9097. //ANY database to do!
  9098. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9099. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9100. }
  9101. else {
  9102. if (url.indexOf("file:") !== -1) {
  9103. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9104. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9105. try {
  9106. var blobURL;
  9107. try {
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. catch (ex) {
  9111. // Chrome doesn't support oneTimeOnly parameter
  9112. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9113. }
  9114. img.src = blobURL;
  9115. usingObjectURL = true;
  9116. }
  9117. catch (e) {
  9118. img.src = "";
  9119. }
  9120. return img;
  9121. }
  9122. }
  9123. noIndexedDB();
  9124. }
  9125. return img;
  9126. };
  9127. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9128. url = Tools.CleanUrl(url);
  9129. url = Tools.PreprocessUrl(url);
  9130. // If file and file input are set
  9131. if (url.indexOf("file:") !== -1) {
  9132. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9133. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9134. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9135. }
  9136. }
  9137. var loadUrl = Tools.BaseUrl + url;
  9138. var aborted = false;
  9139. var fileRequest = {
  9140. onCompleteObservable: new BABYLON.Observable(),
  9141. abort: function () { return aborted = true; },
  9142. };
  9143. var requestFile = function () {
  9144. var request = new XMLHttpRequest();
  9145. var retryHandle = null;
  9146. fileRequest.abort = function () {
  9147. aborted = true;
  9148. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9149. request.abort();
  9150. }
  9151. if (retryHandle !== null) {
  9152. clearTimeout(retryHandle);
  9153. retryHandle = null;
  9154. }
  9155. };
  9156. var retryLoop = function (retryIndex) {
  9157. request.open('GET', loadUrl, true);
  9158. if (useArrayBuffer) {
  9159. request.responseType = "arraybuffer";
  9160. }
  9161. if (onProgress) {
  9162. request.addEventListener("progress", onProgress);
  9163. }
  9164. var onLoadEnd = function () {
  9165. request.removeEventListener("loadend", onLoadEnd);
  9166. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9167. fileRequest.onCompleteObservable.clear();
  9168. };
  9169. request.addEventListener("loadend", onLoadEnd);
  9170. var onReadyStateChange = function () {
  9171. if (aborted) {
  9172. return;
  9173. }
  9174. // In case of undefined state in some browsers.
  9175. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9176. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9177. request.removeEventListener("readystatechange", onReadyStateChange);
  9178. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9179. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9180. return;
  9181. }
  9182. var retryStrategy = Tools.DefaultRetryStrategy;
  9183. if (retryStrategy) {
  9184. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9185. if (waitTime !== -1) {
  9186. // Prevent the request from completing for retry.
  9187. request.removeEventListener("loadend", onLoadEnd);
  9188. request = new XMLHttpRequest();
  9189. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9190. return;
  9191. }
  9192. }
  9193. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9194. if (onError) {
  9195. onError(request, e);
  9196. }
  9197. else {
  9198. throw e;
  9199. }
  9200. }
  9201. };
  9202. request.addEventListener("readystatechange", onReadyStateChange);
  9203. request.send();
  9204. };
  9205. retryLoop(0);
  9206. };
  9207. // Caching all files
  9208. if (database && database.enableSceneOffline) {
  9209. var noIndexedDB_1 = function (request) {
  9210. if (request && request.status > 400) {
  9211. if (onError) {
  9212. onError(request);
  9213. }
  9214. }
  9215. else {
  9216. if (!aborted) {
  9217. requestFile();
  9218. }
  9219. }
  9220. };
  9221. var loadFromIndexedDB = function () {
  9222. // TODO: database needs to support aborting and should return a IFileRequest
  9223. if (aborted) {
  9224. return;
  9225. }
  9226. if (database) {
  9227. database.loadFileFromDB(url, function (data) {
  9228. if (!aborted) {
  9229. onSuccess(data);
  9230. }
  9231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9232. }, onProgress ? function (event) {
  9233. if (!aborted) {
  9234. onProgress(event);
  9235. }
  9236. } : undefined, noIndexedDB_1, useArrayBuffer);
  9237. }
  9238. };
  9239. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9240. }
  9241. else {
  9242. requestFile();
  9243. }
  9244. return fileRequest;
  9245. };
  9246. /**
  9247. * Load a script (identified by an url). When the url returns, the
  9248. * content of this file is added into a new script element, attached to the DOM (body element)
  9249. */
  9250. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9251. var head = document.getElementsByTagName('head')[0];
  9252. var script = document.createElement('script');
  9253. script.type = 'text/javascript';
  9254. script.src = scriptUrl;
  9255. script.onload = function () {
  9256. if (onSuccess) {
  9257. onSuccess();
  9258. }
  9259. };
  9260. script.onerror = function (e) {
  9261. if (onError) {
  9262. onError("Unable to load script '" + scriptUrl + "'", e);
  9263. }
  9264. };
  9265. head.appendChild(script);
  9266. };
  9267. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9268. var reader = new FileReader();
  9269. var request = {
  9270. onCompleteObservable: new BABYLON.Observable(),
  9271. abort: function () { return reader.abort(); },
  9272. };
  9273. reader.onloadend = function (e) {
  9274. request.onCompleteObservable.notifyObservers(request);
  9275. };
  9276. reader.onload = function (e) {
  9277. //target doesn't have result from ts 1.3
  9278. callback(e.target['result']);
  9279. };
  9280. reader.onprogress = progressCallback;
  9281. reader.readAsDataURL(fileToLoad);
  9282. return request;
  9283. };
  9284. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9285. var reader = new FileReader();
  9286. var request = {
  9287. onCompleteObservable: new BABYLON.Observable(),
  9288. abort: function () { return reader.abort(); },
  9289. };
  9290. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9291. reader.onerror = function (e) {
  9292. Tools.Log("Error while reading file: " + fileToLoad.name);
  9293. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9294. };
  9295. reader.onload = function (e) {
  9296. //target doesn't have result from ts 1.3
  9297. callback(e.target['result']);
  9298. };
  9299. if (progressCallBack) {
  9300. reader.onprogress = progressCallBack;
  9301. }
  9302. if (!useArrayBuffer) {
  9303. // Asynchronous read
  9304. reader.readAsText(fileToLoad);
  9305. }
  9306. else {
  9307. reader.readAsArrayBuffer(fileToLoad);
  9308. }
  9309. return request;
  9310. };
  9311. //returns a downloadable url to a file content.
  9312. Tools.FileAsURL = function (content) {
  9313. var fileBlob = new Blob([content]);
  9314. var url = window.URL || window.webkitURL;
  9315. var link = url.createObjectURL(fileBlob);
  9316. return link;
  9317. };
  9318. // Misc.
  9319. Tools.Format = function (value, decimals) {
  9320. if (decimals === void 0) { decimals = 2; }
  9321. return value.toFixed(decimals);
  9322. };
  9323. Tools.CheckExtends = function (v, min, max) {
  9324. if (v.x < min.x)
  9325. min.x = v.x;
  9326. if (v.y < min.y)
  9327. min.y = v.y;
  9328. if (v.z < min.z)
  9329. min.z = v.z;
  9330. if (v.x > max.x)
  9331. max.x = v.x;
  9332. if (v.y > max.y)
  9333. max.y = v.y;
  9334. if (v.z > max.z)
  9335. max.z = v.z;
  9336. };
  9337. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9338. for (var prop in source) {
  9339. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9340. continue;
  9341. }
  9342. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9343. continue;
  9344. }
  9345. var sourceValue = source[prop];
  9346. var typeOfSourceValue = typeof sourceValue;
  9347. if (typeOfSourceValue === "function") {
  9348. continue;
  9349. }
  9350. try {
  9351. if (typeOfSourceValue === "object") {
  9352. if (sourceValue instanceof Array) {
  9353. destination[prop] = [];
  9354. if (sourceValue.length > 0) {
  9355. if (typeof sourceValue[0] == "object") {
  9356. for (var index = 0; index < sourceValue.length; index++) {
  9357. var clonedValue = cloneValue(sourceValue[index], destination);
  9358. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9359. destination[prop].push(clonedValue);
  9360. }
  9361. }
  9362. }
  9363. else {
  9364. destination[prop] = sourceValue.slice(0);
  9365. }
  9366. }
  9367. }
  9368. else {
  9369. destination[prop] = cloneValue(sourceValue, destination);
  9370. }
  9371. }
  9372. else {
  9373. destination[prop] = sourceValue;
  9374. }
  9375. }
  9376. catch (e) {
  9377. // Just ignore error (it could be because of a read-only property)
  9378. }
  9379. }
  9380. };
  9381. Tools.IsEmpty = function (obj) {
  9382. for (var i in obj) {
  9383. if (obj.hasOwnProperty(i)) {
  9384. return false;
  9385. }
  9386. }
  9387. return true;
  9388. };
  9389. Tools.RegisterTopRootEvents = function (events) {
  9390. for (var index = 0; index < events.length; index++) {
  9391. var event = events[index];
  9392. window.addEventListener(event.name, event.handler, false);
  9393. try {
  9394. if (window.parent) {
  9395. window.parent.addEventListener(event.name, event.handler, false);
  9396. }
  9397. }
  9398. catch (e) {
  9399. // Silently fails...
  9400. }
  9401. }
  9402. };
  9403. Tools.UnregisterTopRootEvents = function (events) {
  9404. for (var index = 0; index < events.length; index++) {
  9405. var event = events[index];
  9406. window.removeEventListener(event.name, event.handler);
  9407. try {
  9408. if (window.parent) {
  9409. window.parent.removeEventListener(event.name, event.handler);
  9410. }
  9411. }
  9412. catch (e) {
  9413. // Silently fails...
  9414. }
  9415. }
  9416. };
  9417. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9418. if (mimeType === void 0) { mimeType = "image/png"; }
  9419. // Read the contents of the framebuffer
  9420. var numberOfChannelsByLine = width * 4;
  9421. var halfHeight = height / 2;
  9422. //Reading datas from WebGL
  9423. var data = engine.readPixels(0, 0, width, height);
  9424. //To flip image on Y axis.
  9425. for (var i = 0; i < halfHeight; i++) {
  9426. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9427. var currentCell = j + i * numberOfChannelsByLine;
  9428. var targetLine = height - i - 1;
  9429. var targetCell = j + targetLine * numberOfChannelsByLine;
  9430. var temp = data[currentCell];
  9431. data[currentCell] = data[targetCell];
  9432. data[targetCell] = temp;
  9433. }
  9434. }
  9435. // Create a 2D canvas to store the result
  9436. if (!screenshotCanvas) {
  9437. screenshotCanvas = document.createElement('canvas');
  9438. }
  9439. screenshotCanvas.width = width;
  9440. screenshotCanvas.height = height;
  9441. var context = screenshotCanvas.getContext('2d');
  9442. if (context) {
  9443. // Copy the pixels to a 2D canvas
  9444. var imageData = context.createImageData(width, height);
  9445. var castData = (imageData.data);
  9446. castData.set(data);
  9447. context.putImageData(imageData, 0, 0);
  9448. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9449. }
  9450. };
  9451. /**
  9452. * Converts the canvas data to blob.
  9453. * This acts as a polyfill for browsers not supporting the to blob function.
  9454. * @param canvas Defines the canvas to extract the data from
  9455. * @param successCallback Defines the callback triggered once the data are available
  9456. * @param mimeType Defines the mime type of the result
  9457. */
  9458. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9459. if (mimeType === void 0) { mimeType = "image/png"; }
  9460. // We need HTMLCanvasElement.toBlob for HD screenshots
  9461. if (!canvas.toBlob) {
  9462. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9463. canvas.toBlob = function (callback, type, quality) {
  9464. var _this = this;
  9465. setTimeout(function () {
  9466. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9467. for (var i = 0; i < len; i++) {
  9468. arr[i] = binStr.charCodeAt(i);
  9469. }
  9470. callback(new Blob([arr]));
  9471. });
  9472. };
  9473. }
  9474. canvas.toBlob(function (blob) {
  9475. successCallback(blob);
  9476. }, mimeType);
  9477. };
  9478. /**
  9479. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9480. * @param successCallback Defines the callback triggered once the data are available
  9481. * @param mimeType Defines the mime type of the result
  9482. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9483. */
  9484. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9485. if (mimeType === void 0) { mimeType = "image/png"; }
  9486. if (successCallback) {
  9487. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9488. successCallback(base64Image);
  9489. }
  9490. else {
  9491. this.ToBlob(screenshotCanvas, function (blob) {
  9492. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9493. if (("download" in document.createElement("a"))) {
  9494. if (!fileName) {
  9495. var date = new Date();
  9496. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9497. fileName = "screenshot_" + stringDate + ".png";
  9498. }
  9499. Tools.Download(blob, fileName);
  9500. }
  9501. else {
  9502. var url = URL.createObjectURL(blob);
  9503. var newWindow = window.open("");
  9504. if (!newWindow)
  9505. return;
  9506. var img = newWindow.document.createElement("img");
  9507. img.onload = function () {
  9508. // no longer need to read the blob so it's revoked
  9509. URL.revokeObjectURL(url);
  9510. };
  9511. img.src = url;
  9512. newWindow.document.body.appendChild(img);
  9513. }
  9514. }, mimeType);
  9515. }
  9516. };
  9517. /**
  9518. * Downloads a blob in the browser
  9519. * @param blob defines the blob to download
  9520. * @param fileName defines the name of the downloaded file
  9521. */
  9522. Tools.Download = function (blob, fileName) {
  9523. if (navigator && navigator.msSaveBlob) {
  9524. navigator.msSaveBlob(blob, fileName);
  9525. return;
  9526. }
  9527. var url = window.URL.createObjectURL(blob);
  9528. var a = document.createElement("a");
  9529. document.body.appendChild(a);
  9530. a.style.display = "none";
  9531. a.href = url;
  9532. a.download = fileName;
  9533. a.addEventListener("click", function () {
  9534. if (a.parentElement) {
  9535. a.parentElement.removeChild(a);
  9536. }
  9537. });
  9538. a.click();
  9539. window.URL.revokeObjectURL(url);
  9540. };
  9541. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9542. if (mimeType === void 0) { mimeType = "image/png"; }
  9543. var width;
  9544. var height;
  9545. // If a precision value is specified
  9546. if (size.precision) {
  9547. width = Math.round(engine.getRenderWidth() * size.precision);
  9548. height = Math.round(width / engine.getAspectRatio(camera));
  9549. }
  9550. else if (size.width && size.height) {
  9551. width = size.width;
  9552. height = size.height;
  9553. }
  9554. //If passing only width, computing height to keep display canvas ratio.
  9555. else if (size.width && !size.height) {
  9556. width = size.width;
  9557. height = Math.round(width / engine.getAspectRatio(camera));
  9558. }
  9559. //If passing only height, computing width to keep display canvas ratio.
  9560. else if (size.height && !size.width) {
  9561. height = size.height;
  9562. width = Math.round(height * engine.getAspectRatio(camera));
  9563. }
  9564. //Assuming here that "size" parameter is a number
  9565. else if (!isNaN(size)) {
  9566. height = size;
  9567. width = size;
  9568. }
  9569. else {
  9570. Tools.Error("Invalid 'size' parameter !");
  9571. return;
  9572. }
  9573. if (!screenshotCanvas) {
  9574. screenshotCanvas = document.createElement('canvas');
  9575. }
  9576. screenshotCanvas.width = width;
  9577. screenshotCanvas.height = height;
  9578. var renderContext = screenshotCanvas.getContext("2d");
  9579. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9580. var newWidth = width;
  9581. var newHeight = newWidth / ratio;
  9582. if (newHeight > height) {
  9583. newHeight = height;
  9584. newWidth = newHeight * ratio;
  9585. }
  9586. var offsetX = Math.max(0, width - newWidth) / 2;
  9587. var offsetY = Math.max(0, height - newHeight) / 2;
  9588. var renderingCanvas = engine.getRenderingCanvas();
  9589. if (renderContext && renderingCanvas) {
  9590. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9591. }
  9592. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9593. };
  9594. /**
  9595. * Generates an image screenshot from the specified camera.
  9596. *
  9597. * @param engine The engine to use for rendering
  9598. * @param camera The camera to use for rendering
  9599. * @param size This parameter can be set to a single number or to an object with the
  9600. * following (optional) properties: precision, width, height. If a single number is passed,
  9601. * it will be used for both width and height. If an object is passed, the screenshot size
  9602. * will be derived from the parameters. The precision property is a multiplier allowing
  9603. * rendering at a higher or lower resolution.
  9604. * @param successCallback The callback receives a single parameter which contains the
  9605. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9606. * src parameter of an <img> to display it.
  9607. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9608. * Check your browser for supported MIME types.
  9609. * @param samples Texture samples (default: 1)
  9610. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9611. * @param fileName A name for for the downloaded file.
  9612. * @constructor
  9613. */
  9614. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9615. if (mimeType === void 0) { mimeType = "image/png"; }
  9616. if (samples === void 0) { samples = 1; }
  9617. if (antialiasing === void 0) { antialiasing = false; }
  9618. var width;
  9619. var height;
  9620. //If a precision value is specified
  9621. if (size.precision) {
  9622. width = Math.round(engine.getRenderWidth() * size.precision);
  9623. height = Math.round(width / engine.getAspectRatio(camera));
  9624. size = { width: width, height: height };
  9625. }
  9626. else if (size.width && size.height) {
  9627. width = size.width;
  9628. height = size.height;
  9629. }
  9630. //If passing only width, computing height to keep display canvas ratio.
  9631. else if (size.width && !size.height) {
  9632. width = size.width;
  9633. height = Math.round(width / engine.getAspectRatio(camera));
  9634. size = { width: width, height: height };
  9635. }
  9636. //If passing only height, computing width to keep display canvas ratio.
  9637. else if (size.height && !size.width) {
  9638. height = size.height;
  9639. width = Math.round(height * engine.getAspectRatio(camera));
  9640. size = { width: width, height: height };
  9641. }
  9642. //Assuming here that "size" parameter is a number
  9643. else if (!isNaN(size)) {
  9644. height = size;
  9645. width = size;
  9646. }
  9647. else {
  9648. Tools.Error("Invalid 'size' parameter !");
  9649. return;
  9650. }
  9651. var scene = camera.getScene();
  9652. var previousCamera = null;
  9653. if (scene.activeCamera !== camera) {
  9654. previousCamera = scene.activeCamera;
  9655. scene.activeCamera = camera;
  9656. }
  9657. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9658. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9659. texture.renderList = null;
  9660. texture.samples = samples;
  9661. if (antialiasing) {
  9662. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9663. }
  9664. texture.onAfterRenderObservable.add(function () {
  9665. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9666. });
  9667. scene.incrementRenderId();
  9668. scene.resetCachedMaterial();
  9669. texture.render(true);
  9670. texture.dispose();
  9671. if (previousCamera) {
  9672. scene.activeCamera = previousCamera;
  9673. }
  9674. camera.getProjectionMatrix(true); // Force cache refresh;
  9675. };
  9676. // XHR response validator for local file scenario
  9677. Tools.ValidateXHRData = function (xhr, dataType) {
  9678. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9679. if (dataType === void 0) { dataType = 7; }
  9680. try {
  9681. if (dataType & 1) {
  9682. if (xhr.responseText && xhr.responseText.length > 0) {
  9683. return true;
  9684. }
  9685. else if (dataType === 1) {
  9686. return false;
  9687. }
  9688. }
  9689. if (dataType & 2) {
  9690. // Check header width and height since there is no "TGA" magic number
  9691. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9692. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9693. return true;
  9694. }
  9695. else if (dataType === 2) {
  9696. return false;
  9697. }
  9698. }
  9699. if (dataType & 4) {
  9700. // Check for the "DDS" magic number
  9701. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9702. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9703. return true;
  9704. }
  9705. else {
  9706. return false;
  9707. }
  9708. }
  9709. }
  9710. catch (e) {
  9711. // Global protection
  9712. }
  9713. return false;
  9714. };
  9715. /**
  9716. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9717. * Be aware Math.random() could cause collisions, but:
  9718. * "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"
  9719. */
  9720. Tools.RandomId = function () {
  9721. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9722. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9723. return v.toString(16);
  9724. });
  9725. };
  9726. /**
  9727. * Test if the given uri is a base64 string.
  9728. * @param uri The uri to test
  9729. * @return True if the uri is a base64 string or false otherwise.
  9730. */
  9731. Tools.IsBase64 = function (uri) {
  9732. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9733. };
  9734. /**
  9735. * Decode the given base64 uri.
  9736. * @param uri The uri to decode
  9737. * @return The decoded base64 data.
  9738. */
  9739. Tools.DecodeBase64 = function (uri) {
  9740. var decodedString = atob(uri.split(",")[1]);
  9741. var bufferLength = decodedString.length;
  9742. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9743. for (var i = 0; i < bufferLength; i++) {
  9744. bufferView[i] = decodedString.charCodeAt(i);
  9745. }
  9746. return bufferView.buffer;
  9747. };
  9748. Object.defineProperty(Tools, "NoneLogLevel", {
  9749. get: function () {
  9750. return Tools._NoneLogLevel;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Object.defineProperty(Tools, "MessageLogLevel", {
  9756. get: function () {
  9757. return Tools._MessageLogLevel;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. Object.defineProperty(Tools, "WarningLogLevel", {
  9763. get: function () {
  9764. return Tools._WarningLogLevel;
  9765. },
  9766. enumerable: true,
  9767. configurable: true
  9768. });
  9769. Object.defineProperty(Tools, "ErrorLogLevel", {
  9770. get: function () {
  9771. return Tools._ErrorLogLevel;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(Tools, "AllLogLevel", {
  9777. get: function () {
  9778. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9779. },
  9780. enumerable: true,
  9781. configurable: true
  9782. });
  9783. Tools._AddLogEntry = function (entry) {
  9784. Tools._LogCache = entry + Tools._LogCache;
  9785. if (Tools.OnNewCacheEntry) {
  9786. Tools.OnNewCacheEntry(entry);
  9787. }
  9788. };
  9789. Tools._FormatMessage = function (message) {
  9790. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9791. var date = new Date();
  9792. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9793. };
  9794. Tools._LogDisabled = function (message) {
  9795. // nothing to do
  9796. };
  9797. Tools._LogEnabled = function (message) {
  9798. var formattedMessage = Tools._FormatMessage(message);
  9799. console.log("BJS - " + formattedMessage);
  9800. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9801. Tools._AddLogEntry(entry);
  9802. };
  9803. Tools._WarnDisabled = function (message) {
  9804. // nothing to do
  9805. };
  9806. Tools._WarnEnabled = function (message) {
  9807. var formattedMessage = Tools._FormatMessage(message);
  9808. console.warn("BJS - " + formattedMessage);
  9809. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9810. Tools._AddLogEntry(entry);
  9811. };
  9812. Tools._ErrorDisabled = function (message) {
  9813. // nothing to do
  9814. };
  9815. Tools._ErrorEnabled = function (message) {
  9816. Tools.errorsCount++;
  9817. var formattedMessage = Tools._FormatMessage(message);
  9818. console.error("BJS - " + formattedMessage);
  9819. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9820. Tools._AddLogEntry(entry);
  9821. };
  9822. Object.defineProperty(Tools, "LogCache", {
  9823. get: function () {
  9824. return Tools._LogCache;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Tools.ClearLogCache = function () {
  9830. Tools._LogCache = "";
  9831. Tools.errorsCount = 0;
  9832. };
  9833. Object.defineProperty(Tools, "LogLevels", {
  9834. set: function (level) {
  9835. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9836. Tools.Log = Tools._LogEnabled;
  9837. }
  9838. else {
  9839. Tools.Log = Tools._LogDisabled;
  9840. }
  9841. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9842. Tools.Warn = Tools._WarnEnabled;
  9843. }
  9844. else {
  9845. Tools.Warn = Tools._WarnDisabled;
  9846. }
  9847. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9848. Tools.Error = Tools._ErrorEnabled;
  9849. }
  9850. else {
  9851. Tools.Error = Tools._ErrorDisabled;
  9852. }
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. /**
  9858. * Check if the loaded document was accessed via `file:`-Protocol.
  9859. * @returns boolean
  9860. */
  9861. Tools.IsFileURL = function () {
  9862. return location.protocol === "file:";
  9863. };
  9864. Tools.IsWindowObjectExist = function () {
  9865. return (typeof window) !== "undefined";
  9866. };
  9867. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9868. get: function () {
  9869. return Tools._PerformanceNoneLogLevel;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9875. get: function () {
  9876. return Tools._PerformanceUserMarkLogLevel;
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9882. get: function () {
  9883. return Tools._PerformanceConsoleLogLevel;
  9884. },
  9885. enumerable: true,
  9886. configurable: true
  9887. });
  9888. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9889. set: function (level) {
  9890. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9891. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9892. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9893. return;
  9894. }
  9895. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9896. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9897. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9898. return;
  9899. }
  9900. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9901. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9907. };
  9908. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9909. };
  9910. Tools._StartUserMark = function (counterName, condition) {
  9911. if (condition === void 0) { condition = true; }
  9912. if (!Tools._performance) {
  9913. if (!Tools.IsWindowObjectExist()) {
  9914. return;
  9915. }
  9916. Tools._performance = window.performance;
  9917. }
  9918. if (!condition || !Tools._performance.mark) {
  9919. return;
  9920. }
  9921. Tools._performance.mark(counterName + "-Begin");
  9922. };
  9923. Tools._EndUserMark = function (counterName, condition) {
  9924. if (condition === void 0) { condition = true; }
  9925. if (!condition || !Tools._performance.mark) {
  9926. return;
  9927. }
  9928. Tools._performance.mark(counterName + "-End");
  9929. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9930. };
  9931. Tools._StartPerformanceConsole = function (counterName, condition) {
  9932. if (condition === void 0) { condition = true; }
  9933. if (!condition) {
  9934. return;
  9935. }
  9936. Tools._StartUserMark(counterName, condition);
  9937. if (console.time) {
  9938. console.time(counterName);
  9939. }
  9940. };
  9941. Tools._EndPerformanceConsole = function (counterName, condition) {
  9942. if (condition === void 0) { condition = true; }
  9943. if (!condition) {
  9944. return;
  9945. }
  9946. Tools._EndUserMark(counterName, condition);
  9947. if (console.time) {
  9948. console.timeEnd(counterName);
  9949. }
  9950. };
  9951. Object.defineProperty(Tools, "Now", {
  9952. get: function () {
  9953. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9954. return window.performance.now();
  9955. }
  9956. return Date.now();
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. /**
  9962. * This method will return the name of the class used to create the instance of the given object.
  9963. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9964. * @param object the object to get the class name from
  9965. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9966. */
  9967. Tools.GetClassName = function (object, isType) {
  9968. if (isType === void 0) { isType = false; }
  9969. var name = null;
  9970. if (!isType && object.getClassName) {
  9971. name = object.getClassName();
  9972. }
  9973. else {
  9974. if (object instanceof Object) {
  9975. var classObj = isType ? object : Object.getPrototypeOf(object);
  9976. name = classObj.constructor["__bjsclassName__"];
  9977. }
  9978. if (!name) {
  9979. name = typeof object;
  9980. }
  9981. }
  9982. return name;
  9983. };
  9984. Tools.First = function (array, predicate) {
  9985. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9986. var el = array_1[_i];
  9987. if (predicate(el)) {
  9988. return el;
  9989. }
  9990. }
  9991. return null;
  9992. };
  9993. /**
  9994. * This method will return the name of the full name of the class, including its owning module (if any).
  9995. * 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).
  9996. * @param object the object to get the class name from
  9997. * @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.
  9998. */
  9999. Tools.getFullClassName = function (object, isType) {
  10000. if (isType === void 0) { isType = false; }
  10001. var className = null;
  10002. var moduleName = null;
  10003. if (!isType && object.getClassName) {
  10004. className = object.getClassName();
  10005. }
  10006. else {
  10007. if (object instanceof Object) {
  10008. var classObj = isType ? object : Object.getPrototypeOf(object);
  10009. className = classObj.constructor["__bjsclassName__"];
  10010. moduleName = classObj.constructor["__bjsmoduleName__"];
  10011. }
  10012. if (!className) {
  10013. className = typeof object;
  10014. }
  10015. }
  10016. if (!className) {
  10017. return null;
  10018. }
  10019. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10020. };
  10021. /**
  10022. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10023. * @param array
  10024. */
  10025. Tools.arrayOrStringFeeder = function (array) {
  10026. return function (index) {
  10027. if (index >= array.length) {
  10028. return null;
  10029. }
  10030. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10031. if (val && val.getHashCode) {
  10032. val = val.getHashCode();
  10033. }
  10034. if (typeof val === "string") {
  10035. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10036. }
  10037. return val;
  10038. };
  10039. };
  10040. /**
  10041. * Compute the hashCode of a stream of number
  10042. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10043. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10044. * @return the hash code computed
  10045. */
  10046. Tools.hashCodeFromStream = function (feeder) {
  10047. // Based from here: http://stackoverflow.com/a/7616484/802124
  10048. var hash = 0;
  10049. var index = 0;
  10050. var chr = feeder(index++);
  10051. while (chr != null) {
  10052. hash = ((hash << 5) - hash) + chr;
  10053. hash |= 0; // Convert to 32bit integer
  10054. chr = feeder(index++);
  10055. }
  10056. return hash;
  10057. };
  10058. /**
  10059. * Returns a promise that resolves after the given amount of time.
  10060. * @param delay Number of milliseconds to delay
  10061. * @returns Promise that resolves after the given amount of time
  10062. */
  10063. Tools.DelayAsync = function (delay) {
  10064. return new Promise(function (resolve) {
  10065. setTimeout(function () {
  10066. resolve();
  10067. }, delay);
  10068. });
  10069. };
  10070. /**
  10071. * Gets the current gradient from an array of IValueGradient
  10072. * @param ratio defines the current ratio to get
  10073. * @param gradients defines the array of IValueGradient
  10074. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10075. */
  10076. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10077. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10078. var currentGradient = gradients[gradientIndex];
  10079. var nextGradient = gradients[gradientIndex + 1];
  10080. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10081. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10082. updateFunc(currentGradient, nextGradient, scale);
  10083. }
  10084. }
  10085. };
  10086. Tools.BaseUrl = "";
  10087. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10088. /**
  10089. * Default behaviour for cors in the application.
  10090. * It can be a string if the expected behavior is identical in the entire app.
  10091. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10092. */
  10093. Tools.CorsBehavior = "anonymous";
  10094. Tools.UseFallbackTexture = true;
  10095. /**
  10096. * Use this object to register external classes like custom textures or material
  10097. * to allow the laoders to instantiate them
  10098. */
  10099. Tools.RegisteredExternalClasses = {};
  10100. // Used in case of a texture loading problem
  10101. 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";
  10102. Tools._tmpFloatArray = new Float32Array(1);
  10103. Tools.PreprocessUrl = function (url) {
  10104. return url;
  10105. };
  10106. // Logs
  10107. Tools._NoneLogLevel = 0;
  10108. Tools._MessageLogLevel = 1;
  10109. Tools._WarningLogLevel = 2;
  10110. Tools._ErrorLogLevel = 4;
  10111. Tools._LogCache = "";
  10112. Tools.errorsCount = 0;
  10113. Tools.Log = Tools._LogEnabled;
  10114. Tools.Warn = Tools._WarnEnabled;
  10115. Tools.Error = Tools._ErrorEnabled;
  10116. // Performances
  10117. Tools._PerformanceNoneLogLevel = 0;
  10118. Tools._PerformanceUserMarkLogLevel = 1;
  10119. Tools._PerformanceConsoleLogLevel = 2;
  10120. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10121. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10122. return Tools;
  10123. }());
  10124. BABYLON.Tools = Tools;
  10125. /**
  10126. * This class is used to track a performance counter which is number based.
  10127. * The user has access to many properties which give statistics of different nature
  10128. *
  10129. * The implementer can track two kinds of Performance Counter: time and count
  10130. * 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.
  10131. * 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.
  10132. */
  10133. var PerfCounter = /** @class */ (function () {
  10134. function PerfCounter() {
  10135. this._startMonitoringTime = 0;
  10136. this._min = 0;
  10137. this._max = 0;
  10138. this._average = 0;
  10139. this._lastSecAverage = 0;
  10140. this._current = 0;
  10141. this._totalValueCount = 0;
  10142. this._totalAccumulated = 0;
  10143. this._lastSecAccumulated = 0;
  10144. this._lastSecTime = 0;
  10145. this._lastSecValueCount = 0;
  10146. }
  10147. Object.defineProperty(PerfCounter.prototype, "min", {
  10148. /**
  10149. * Returns the smallest value ever
  10150. */
  10151. get: function () {
  10152. return this._min;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(PerfCounter.prototype, "max", {
  10158. /**
  10159. * Returns the biggest value ever
  10160. */
  10161. get: function () {
  10162. return this._max;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "average", {
  10168. /**
  10169. * Returns the average value since the performance counter is running
  10170. */
  10171. get: function () {
  10172. return this._average;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10178. /**
  10179. * Returns the average value of the last second the counter was monitored
  10180. */
  10181. get: function () {
  10182. return this._lastSecAverage;
  10183. },
  10184. enumerable: true,
  10185. configurable: true
  10186. });
  10187. Object.defineProperty(PerfCounter.prototype, "current", {
  10188. /**
  10189. * Returns the current value
  10190. */
  10191. get: function () {
  10192. return this._current;
  10193. },
  10194. enumerable: true,
  10195. configurable: true
  10196. });
  10197. Object.defineProperty(PerfCounter.prototype, "total", {
  10198. get: function () {
  10199. return this._totalAccumulated;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Object.defineProperty(PerfCounter.prototype, "count", {
  10205. get: function () {
  10206. return this._totalValueCount;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. /**
  10212. * Call this method to start monitoring a new frame.
  10213. * 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.
  10214. */
  10215. PerfCounter.prototype.fetchNewFrame = function () {
  10216. this._totalValueCount++;
  10217. this._current = 0;
  10218. this._lastSecValueCount++;
  10219. };
  10220. /**
  10221. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10222. * @param newCount the count value to add to the monitored count
  10223. * @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.
  10224. */
  10225. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10226. if (!PerfCounter.Enabled) {
  10227. return;
  10228. }
  10229. this._current += newCount;
  10230. if (fetchResult) {
  10231. this._fetchResult();
  10232. }
  10233. };
  10234. /**
  10235. * Start monitoring this performance counter
  10236. */
  10237. PerfCounter.prototype.beginMonitoring = function () {
  10238. if (!PerfCounter.Enabled) {
  10239. return;
  10240. }
  10241. this._startMonitoringTime = Tools.Now;
  10242. };
  10243. /**
  10244. * Compute the time lapsed since the previous beginMonitoring() call.
  10245. * @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
  10246. */
  10247. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10248. if (newFrame === void 0) { newFrame = true; }
  10249. if (!PerfCounter.Enabled) {
  10250. return;
  10251. }
  10252. if (newFrame) {
  10253. this.fetchNewFrame();
  10254. }
  10255. var currentTime = Tools.Now;
  10256. this._current = currentTime - this._startMonitoringTime;
  10257. if (newFrame) {
  10258. this._fetchResult();
  10259. }
  10260. };
  10261. PerfCounter.prototype._fetchResult = function () {
  10262. this._totalAccumulated += this._current;
  10263. this._lastSecAccumulated += this._current;
  10264. // Min/Max update
  10265. this._min = Math.min(this._min, this._current);
  10266. this._max = Math.max(this._max, this._current);
  10267. this._average = this._totalAccumulated / this._totalValueCount;
  10268. // Reset last sec?
  10269. var now = Tools.Now;
  10270. if ((now - this._lastSecTime) > 1000) {
  10271. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10272. this._lastSecTime = now;
  10273. this._lastSecAccumulated = 0;
  10274. this._lastSecValueCount = 0;
  10275. }
  10276. };
  10277. PerfCounter.Enabled = true;
  10278. return PerfCounter;
  10279. }());
  10280. BABYLON.PerfCounter = PerfCounter;
  10281. /**
  10282. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10283. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10284. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10285. * @param name The name of the class, case should be preserved
  10286. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10287. */
  10288. function className(name, module) {
  10289. return function (target) {
  10290. target["__bjsclassName__"] = name;
  10291. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10292. };
  10293. }
  10294. BABYLON.className = className;
  10295. /**
  10296. * An implementation of a loop for asynchronous functions.
  10297. */
  10298. var AsyncLoop = /** @class */ (function () {
  10299. /**
  10300. * Constroctor.
  10301. * @param iterations the number of iterations.
  10302. * @param _fn the function to run each iteration
  10303. * @param _successCallback the callback that will be called upon succesful execution
  10304. * @param offset starting offset.
  10305. */
  10306. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10307. if (offset === void 0) { offset = 0; }
  10308. this.iterations = iterations;
  10309. this._fn = _fn;
  10310. this._successCallback = _successCallback;
  10311. this.index = offset - 1;
  10312. this._done = false;
  10313. }
  10314. /**
  10315. * Execute the next iteration. Must be called after the last iteration was finished.
  10316. */
  10317. AsyncLoop.prototype.executeNext = function () {
  10318. if (!this._done) {
  10319. if (this.index + 1 < this.iterations) {
  10320. ++this.index;
  10321. this._fn(this);
  10322. }
  10323. else {
  10324. this.breakLoop();
  10325. }
  10326. }
  10327. };
  10328. /**
  10329. * Break the loop and run the success callback.
  10330. */
  10331. AsyncLoop.prototype.breakLoop = function () {
  10332. this._done = true;
  10333. this._successCallback();
  10334. };
  10335. /**
  10336. * Helper function
  10337. */
  10338. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10339. if (offset === void 0) { offset = 0; }
  10340. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10341. loop.executeNext();
  10342. return loop;
  10343. };
  10344. /**
  10345. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10346. * @param iterations total number of iterations
  10347. * @param syncedIterations number of synchronous iterations in each async iteration.
  10348. * @param fn the function to call each iteration.
  10349. * @param callback a success call back that will be called when iterating stops.
  10350. * @param breakFunction a break condition (optional)
  10351. * @param timeout timeout settings for the setTimeout function. default - 0.
  10352. * @constructor
  10353. */
  10354. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10355. if (timeout === void 0) { timeout = 0; }
  10356. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10357. if (breakFunction && breakFunction())
  10358. loop.breakLoop();
  10359. else {
  10360. setTimeout(function () {
  10361. for (var i = 0; i < syncedIterations; ++i) {
  10362. var iteration = (loop.index * syncedIterations) + i;
  10363. if (iteration >= iterations)
  10364. break;
  10365. fn(iteration);
  10366. if (breakFunction && breakFunction()) {
  10367. loop.breakLoop();
  10368. break;
  10369. }
  10370. }
  10371. loop.executeNext();
  10372. }, timeout);
  10373. }
  10374. }, callback);
  10375. };
  10376. return AsyncLoop;
  10377. }());
  10378. BABYLON.AsyncLoop = AsyncLoop;
  10379. })(BABYLON || (BABYLON = {}));
  10380. //# sourceMappingURL=babylon.tools.js.map
  10381. var BABYLON;
  10382. (function (BABYLON) {
  10383. var PromiseStates;
  10384. (function (PromiseStates) {
  10385. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10386. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10387. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10388. })(PromiseStates || (PromiseStates = {}));
  10389. var FulFillmentAgregator = /** @class */ (function () {
  10390. function FulFillmentAgregator() {
  10391. this.count = 0;
  10392. this.target = 0;
  10393. this.results = [];
  10394. }
  10395. return FulFillmentAgregator;
  10396. }());
  10397. var InternalPromise = /** @class */ (function () {
  10398. function InternalPromise(resolver) {
  10399. var _this = this;
  10400. this._state = PromiseStates.Pending;
  10401. this._children = new Array();
  10402. this._rejectWasConsumed = false;
  10403. if (!resolver) {
  10404. return;
  10405. }
  10406. try {
  10407. resolver(function (value) {
  10408. _this._resolve(value);
  10409. }, function (reason) {
  10410. _this._reject(reason);
  10411. });
  10412. }
  10413. catch (e) {
  10414. this._reject(e);
  10415. }
  10416. }
  10417. Object.defineProperty(InternalPromise.prototype, "_result", {
  10418. get: function () {
  10419. return this._resultValue;
  10420. },
  10421. set: function (value) {
  10422. this._resultValue = value;
  10423. if (this._parent && this._parent._result === undefined) {
  10424. this._parent._result = value;
  10425. }
  10426. },
  10427. enumerable: true,
  10428. configurable: true
  10429. });
  10430. InternalPromise.prototype.catch = function (onRejected) {
  10431. return this.then(undefined, onRejected);
  10432. };
  10433. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10434. var _this = this;
  10435. var newPromise = new InternalPromise();
  10436. newPromise._onFulfilled = onFulfilled;
  10437. newPromise._onRejected = onRejected;
  10438. // Composition
  10439. this._children.push(newPromise);
  10440. newPromise._parent = this;
  10441. if (this._state !== PromiseStates.Pending) {
  10442. BABYLON.Tools.SetImmediate(function () {
  10443. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10444. var returnedValue = newPromise._resolve(_this._result);
  10445. if (returnedValue !== undefined && returnedValue !== null) {
  10446. if (returnedValue._state !== undefined) {
  10447. var returnedPromise = returnedValue;
  10448. newPromise._children.push(returnedPromise);
  10449. returnedPromise._parent = newPromise;
  10450. newPromise = returnedPromise;
  10451. }
  10452. else {
  10453. newPromise._result = returnedValue;
  10454. }
  10455. }
  10456. }
  10457. else {
  10458. newPromise._reject(_this._reason);
  10459. }
  10460. });
  10461. }
  10462. return newPromise;
  10463. };
  10464. InternalPromise.prototype._moveChildren = function (children) {
  10465. var _this = this;
  10466. var _a;
  10467. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10468. this._children.forEach(function (child) {
  10469. child._parent = _this;
  10470. });
  10471. if (this._state === PromiseStates.Fulfilled) {
  10472. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10473. var child = _b[_i];
  10474. child._resolve(this._result);
  10475. }
  10476. }
  10477. else if (this._state === PromiseStates.Rejected) {
  10478. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10479. var child = _d[_c];
  10480. child._reject(this._reason);
  10481. }
  10482. }
  10483. };
  10484. InternalPromise.prototype._resolve = function (value) {
  10485. try {
  10486. this._state = PromiseStates.Fulfilled;
  10487. var returnedValue = null;
  10488. if (this._onFulfilled) {
  10489. returnedValue = this._onFulfilled(value);
  10490. }
  10491. if (returnedValue !== undefined && returnedValue !== null) {
  10492. if (returnedValue._state !== undefined) {
  10493. // Transmit children
  10494. var returnedPromise = returnedValue;
  10495. returnedPromise._parent = this;
  10496. returnedPromise._moveChildren(this._children);
  10497. value = returnedPromise._result;
  10498. }
  10499. else {
  10500. value = returnedValue;
  10501. }
  10502. }
  10503. this._result = value;
  10504. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10505. var child = _a[_i];
  10506. child._resolve(value);
  10507. }
  10508. this._children.length = 0;
  10509. delete this._onFulfilled;
  10510. delete this._onRejected;
  10511. }
  10512. catch (e) {
  10513. this._reject(e, true);
  10514. }
  10515. };
  10516. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10517. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10518. this._state = PromiseStates.Rejected;
  10519. this._reason = reason;
  10520. if (this._onRejected && !onLocalThrow) {
  10521. try {
  10522. this._onRejected(reason);
  10523. this._rejectWasConsumed = true;
  10524. }
  10525. catch (e) {
  10526. reason = e;
  10527. }
  10528. }
  10529. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10530. var child = _a[_i];
  10531. if (this._rejectWasConsumed) {
  10532. child._resolve(null);
  10533. }
  10534. else {
  10535. child._reject(reason);
  10536. }
  10537. }
  10538. this._children.length = 0;
  10539. delete this._onFulfilled;
  10540. delete this._onRejected;
  10541. };
  10542. InternalPromise.resolve = function (value) {
  10543. var newPromise = new InternalPromise();
  10544. newPromise._resolve(value);
  10545. return newPromise;
  10546. };
  10547. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10548. promise.then(function (value) {
  10549. agregator.results[index] = value;
  10550. agregator.count++;
  10551. if (agregator.count === agregator.target) {
  10552. agregator.rootPromise._resolve(agregator.results);
  10553. }
  10554. return null;
  10555. }, function (reason) {
  10556. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10557. agregator.rootPromise._reject(reason);
  10558. }
  10559. });
  10560. };
  10561. InternalPromise.all = function (promises) {
  10562. var newPromise = new InternalPromise();
  10563. var agregator = new FulFillmentAgregator();
  10564. agregator.target = promises.length;
  10565. agregator.rootPromise = newPromise;
  10566. if (promises.length) {
  10567. for (var index = 0; index < promises.length; index++) {
  10568. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10569. }
  10570. }
  10571. else {
  10572. newPromise._resolve([]);
  10573. }
  10574. return newPromise;
  10575. };
  10576. InternalPromise.race = function (promises) {
  10577. var newPromise = new InternalPromise();
  10578. if (promises.length) {
  10579. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10580. var promise = promises_1[_i];
  10581. promise.then(function (value) {
  10582. if (newPromise) {
  10583. newPromise._resolve(value);
  10584. newPromise = null;
  10585. }
  10586. return null;
  10587. }, function (reason) {
  10588. if (newPromise) {
  10589. newPromise._reject(reason);
  10590. newPromise = null;
  10591. }
  10592. });
  10593. }
  10594. }
  10595. return newPromise;
  10596. };
  10597. return InternalPromise;
  10598. }());
  10599. /**
  10600. * Helper class that provides a small promise polyfill
  10601. */
  10602. var PromisePolyfill = /** @class */ (function () {
  10603. function PromisePolyfill() {
  10604. }
  10605. /**
  10606. * Static function used to check if the polyfill is required
  10607. * If this is the case then the function will inject the polyfill to window.Promise
  10608. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10609. */
  10610. PromisePolyfill.Apply = function (force) {
  10611. if (force === void 0) { force = false; }
  10612. if (force || typeof Promise === 'undefined') {
  10613. var root = window;
  10614. root.Promise = InternalPromise;
  10615. }
  10616. };
  10617. return PromisePolyfill;
  10618. }());
  10619. BABYLON.PromisePolyfill = PromisePolyfill;
  10620. })(BABYLON || (BABYLON = {}));
  10621. //# sourceMappingURL=babylon.promise.js.map
  10622. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10623. var BABYLON;
  10624. (function (BABYLON) {
  10625. /**
  10626. * Helper class to push actions to a pool of workers.
  10627. */
  10628. var WorkerPool = /** @class */ (function () {
  10629. /**
  10630. * Constructor
  10631. * @param workers Array of workers to use for actions
  10632. */
  10633. function WorkerPool(workers) {
  10634. this._pendingActions = new Array();
  10635. this._workerInfos = workers.map(function (worker) { return ({
  10636. worker: worker,
  10637. active: false
  10638. }); });
  10639. }
  10640. /**
  10641. * Terminates all workers and clears any pending actions.
  10642. */
  10643. WorkerPool.prototype.dispose = function () {
  10644. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10645. var workerInfo = _a[_i];
  10646. workerInfo.worker.terminate();
  10647. }
  10648. delete this._workerInfos;
  10649. delete this._pendingActions;
  10650. };
  10651. /**
  10652. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10653. * pended until a worker has completed its action.
  10654. * @param action The action to perform. Call onComplete when the action is complete.
  10655. */
  10656. WorkerPool.prototype.push = function (action) {
  10657. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10658. var workerInfo = _a[_i];
  10659. if (!workerInfo.active) {
  10660. this._execute(workerInfo, action);
  10661. return;
  10662. }
  10663. }
  10664. this._pendingActions.push(action);
  10665. };
  10666. WorkerPool.prototype._execute = function (workerInfo, action) {
  10667. var _this = this;
  10668. workerInfo.active = true;
  10669. action(workerInfo.worker, function () {
  10670. workerInfo.active = false;
  10671. var nextAction = _this._pendingActions.shift();
  10672. if (nextAction) {
  10673. _this._execute(workerInfo, nextAction);
  10674. }
  10675. });
  10676. };
  10677. return WorkerPool;
  10678. }());
  10679. BABYLON.WorkerPool = WorkerPool;
  10680. })(BABYLON || (BABYLON = {}));
  10681. //# sourceMappingURL=babylon.workerPool.js.map
  10682. var BABYLON;
  10683. (function (BABYLON) {
  10684. /**
  10685. * @hidden
  10686. **/
  10687. var _AlphaState = /** @class */ (function () {
  10688. /**
  10689. * Initializes the state.
  10690. */
  10691. function _AlphaState() {
  10692. this._isAlphaBlendDirty = false;
  10693. this._isBlendFunctionParametersDirty = false;
  10694. this._isBlendEquationParametersDirty = false;
  10695. this._isBlendConstantsDirty = false;
  10696. this._alphaBlend = false;
  10697. this._blendFunctionParameters = new Array(4);
  10698. this._blendEquationParameters = new Array(2);
  10699. this._blendConstants = new Array(4);
  10700. this.reset();
  10701. }
  10702. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10703. get: function () {
  10704. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10705. },
  10706. enumerable: true,
  10707. configurable: true
  10708. });
  10709. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10710. get: function () {
  10711. return this._alphaBlend;
  10712. },
  10713. set: function (value) {
  10714. if (this._alphaBlend === value) {
  10715. return;
  10716. }
  10717. this._alphaBlend = value;
  10718. this._isAlphaBlendDirty = true;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10724. if (this._blendConstants[0] === r &&
  10725. this._blendConstants[1] === g &&
  10726. this._blendConstants[2] === b &&
  10727. this._blendConstants[3] === a) {
  10728. return;
  10729. }
  10730. this._blendConstants[0] = r;
  10731. this._blendConstants[1] = g;
  10732. this._blendConstants[2] = b;
  10733. this._blendConstants[3] = a;
  10734. this._isBlendConstantsDirty = true;
  10735. };
  10736. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10737. if (this._blendFunctionParameters[0] === value0 &&
  10738. this._blendFunctionParameters[1] === value1 &&
  10739. this._blendFunctionParameters[2] === value2 &&
  10740. this._blendFunctionParameters[3] === value3) {
  10741. return;
  10742. }
  10743. this._blendFunctionParameters[0] = value0;
  10744. this._blendFunctionParameters[1] = value1;
  10745. this._blendFunctionParameters[2] = value2;
  10746. this._blendFunctionParameters[3] = value3;
  10747. this._isBlendFunctionParametersDirty = true;
  10748. };
  10749. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10750. if (this._blendEquationParameters[0] === rgb &&
  10751. this._blendEquationParameters[1] === alpha) {
  10752. return;
  10753. }
  10754. this._blendEquationParameters[0] = rgb;
  10755. this._blendEquationParameters[1] = alpha;
  10756. this._isBlendEquationParametersDirty = true;
  10757. };
  10758. _AlphaState.prototype.reset = function () {
  10759. this._alphaBlend = false;
  10760. this._blendFunctionParameters[0] = null;
  10761. this._blendFunctionParameters[1] = null;
  10762. this._blendFunctionParameters[2] = null;
  10763. this._blendFunctionParameters[3] = null;
  10764. this._blendEquationParameters[0] = null;
  10765. this._blendEquationParameters[1] = null;
  10766. this._blendConstants[0] = null;
  10767. this._blendConstants[1] = null;
  10768. this._blendConstants[2] = null;
  10769. this._blendConstants[3] = null;
  10770. this._isAlphaBlendDirty = true;
  10771. this._isBlendFunctionParametersDirty = false;
  10772. this._isBlendEquationParametersDirty = false;
  10773. this._isBlendConstantsDirty = false;
  10774. };
  10775. _AlphaState.prototype.apply = function (gl) {
  10776. if (!this.isDirty) {
  10777. return;
  10778. }
  10779. // Alpha blend
  10780. if (this._isAlphaBlendDirty) {
  10781. if (this._alphaBlend) {
  10782. gl.enable(gl.BLEND);
  10783. }
  10784. else {
  10785. gl.disable(gl.BLEND);
  10786. }
  10787. this._isAlphaBlendDirty = false;
  10788. }
  10789. // Alpha function
  10790. if (this._isBlendFunctionParametersDirty) {
  10791. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10792. this._isBlendFunctionParametersDirty = false;
  10793. }
  10794. // Alpha equation
  10795. if (this._isBlendEquationParametersDirty) {
  10796. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10797. this._isBlendEquationParametersDirty = false;
  10798. }
  10799. // Constants
  10800. if (this._isBlendConstantsDirty) {
  10801. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10802. this._isBlendConstantsDirty = false;
  10803. }
  10804. };
  10805. return _AlphaState;
  10806. }());
  10807. BABYLON._AlphaState = _AlphaState;
  10808. })(BABYLON || (BABYLON = {}));
  10809. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10810. var BABYLON;
  10811. (function (BABYLON) {
  10812. /**
  10813. * @hidden
  10814. **/
  10815. var _DepthCullingState = /** @class */ (function () {
  10816. /**
  10817. * Initializes the state.
  10818. */
  10819. function _DepthCullingState() {
  10820. this._isDepthTestDirty = false;
  10821. this._isDepthMaskDirty = false;
  10822. this._isDepthFuncDirty = false;
  10823. this._isCullFaceDirty = false;
  10824. this._isCullDirty = false;
  10825. this._isZOffsetDirty = false;
  10826. this._isFrontFaceDirty = false;
  10827. this.reset();
  10828. }
  10829. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10830. get: function () {
  10831. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10837. get: function () {
  10838. return this._zOffset;
  10839. },
  10840. set: function (value) {
  10841. if (this._zOffset === value) {
  10842. return;
  10843. }
  10844. this._zOffset = value;
  10845. this._isZOffsetDirty = true;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10851. get: function () {
  10852. return this._cullFace;
  10853. },
  10854. set: function (value) {
  10855. if (this._cullFace === value) {
  10856. return;
  10857. }
  10858. this._cullFace = value;
  10859. this._isCullFaceDirty = true;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10865. get: function () {
  10866. return this._cull;
  10867. },
  10868. set: function (value) {
  10869. if (this._cull === value) {
  10870. return;
  10871. }
  10872. this._cull = value;
  10873. this._isCullDirty = true;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10879. get: function () {
  10880. return this._depthFunc;
  10881. },
  10882. set: function (value) {
  10883. if (this._depthFunc === value) {
  10884. return;
  10885. }
  10886. this._depthFunc = value;
  10887. this._isDepthFuncDirty = true;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10893. get: function () {
  10894. return this._depthMask;
  10895. },
  10896. set: function (value) {
  10897. if (this._depthMask === value) {
  10898. return;
  10899. }
  10900. this._depthMask = value;
  10901. this._isDepthMaskDirty = true;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10907. get: function () {
  10908. return this._depthTest;
  10909. },
  10910. set: function (value) {
  10911. if (this._depthTest === value) {
  10912. return;
  10913. }
  10914. this._depthTest = value;
  10915. this._isDepthTestDirty = true;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10921. get: function () {
  10922. return this._frontFace;
  10923. },
  10924. set: function (value) {
  10925. if (this._frontFace === value) {
  10926. return;
  10927. }
  10928. this._frontFace = value;
  10929. this._isFrontFaceDirty = true;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. _DepthCullingState.prototype.reset = function () {
  10935. this._depthMask = true;
  10936. this._depthTest = true;
  10937. this._depthFunc = null;
  10938. this._cullFace = null;
  10939. this._cull = null;
  10940. this._zOffset = 0;
  10941. this._frontFace = null;
  10942. this._isDepthTestDirty = true;
  10943. this._isDepthMaskDirty = true;
  10944. this._isDepthFuncDirty = false;
  10945. this._isCullFaceDirty = false;
  10946. this._isCullDirty = false;
  10947. this._isZOffsetDirty = false;
  10948. this._isFrontFaceDirty = false;
  10949. };
  10950. _DepthCullingState.prototype.apply = function (gl) {
  10951. if (!this.isDirty) {
  10952. return;
  10953. }
  10954. // Cull
  10955. if (this._isCullDirty) {
  10956. if (this.cull) {
  10957. gl.enable(gl.CULL_FACE);
  10958. }
  10959. else {
  10960. gl.disable(gl.CULL_FACE);
  10961. }
  10962. this._isCullDirty = false;
  10963. }
  10964. // Cull face
  10965. if (this._isCullFaceDirty) {
  10966. gl.cullFace(this.cullFace);
  10967. this._isCullFaceDirty = false;
  10968. }
  10969. // Depth mask
  10970. if (this._isDepthMaskDirty) {
  10971. gl.depthMask(this.depthMask);
  10972. this._isDepthMaskDirty = false;
  10973. }
  10974. // Depth test
  10975. if (this._isDepthTestDirty) {
  10976. if (this.depthTest) {
  10977. gl.enable(gl.DEPTH_TEST);
  10978. }
  10979. else {
  10980. gl.disable(gl.DEPTH_TEST);
  10981. }
  10982. this._isDepthTestDirty = false;
  10983. }
  10984. // Depth func
  10985. if (this._isDepthFuncDirty) {
  10986. gl.depthFunc(this.depthFunc);
  10987. this._isDepthFuncDirty = false;
  10988. }
  10989. // zOffset
  10990. if (this._isZOffsetDirty) {
  10991. if (this.zOffset) {
  10992. gl.enable(gl.POLYGON_OFFSET_FILL);
  10993. gl.polygonOffset(this.zOffset, 0);
  10994. }
  10995. else {
  10996. gl.disable(gl.POLYGON_OFFSET_FILL);
  10997. }
  10998. this._isZOffsetDirty = false;
  10999. }
  11000. // Front face
  11001. if (this._isFrontFaceDirty) {
  11002. gl.frontFace(this.frontFace);
  11003. this._isFrontFaceDirty = false;
  11004. }
  11005. };
  11006. return _DepthCullingState;
  11007. }());
  11008. BABYLON._DepthCullingState = _DepthCullingState;
  11009. })(BABYLON || (BABYLON = {}));
  11010. //# sourceMappingURL=babylon.depthCullingState.js.map
  11011. var BABYLON;
  11012. (function (BABYLON) {
  11013. /**
  11014. * @hidden
  11015. **/
  11016. var _StencilState = /** @class */ (function () {
  11017. function _StencilState() {
  11018. this._isStencilTestDirty = false;
  11019. this._isStencilMaskDirty = false;
  11020. this._isStencilFuncDirty = false;
  11021. this._isStencilOpDirty = false;
  11022. this.reset();
  11023. }
  11024. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11025. get: function () {
  11026. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11032. get: function () {
  11033. return this._stencilFunc;
  11034. },
  11035. set: function (value) {
  11036. if (this._stencilFunc === value) {
  11037. return;
  11038. }
  11039. this._stencilFunc = value;
  11040. this._isStencilFuncDirty = true;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11046. get: function () {
  11047. return this._stencilFuncRef;
  11048. },
  11049. set: function (value) {
  11050. if (this._stencilFuncRef === value) {
  11051. return;
  11052. }
  11053. this._stencilFuncRef = value;
  11054. this._isStencilFuncDirty = true;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11060. get: function () {
  11061. return this._stencilFuncMask;
  11062. },
  11063. set: function (value) {
  11064. if (this._stencilFuncMask === value) {
  11065. return;
  11066. }
  11067. this._stencilFuncMask = value;
  11068. this._isStencilFuncDirty = true;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11074. get: function () {
  11075. return this._stencilOpStencilFail;
  11076. },
  11077. set: function (value) {
  11078. if (this._stencilOpStencilFail === value) {
  11079. return;
  11080. }
  11081. this._stencilOpStencilFail = value;
  11082. this._isStencilOpDirty = true;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11088. get: function () {
  11089. return this._stencilOpDepthFail;
  11090. },
  11091. set: function (value) {
  11092. if (this._stencilOpDepthFail === value) {
  11093. return;
  11094. }
  11095. this._stencilOpDepthFail = value;
  11096. this._isStencilOpDirty = true;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11102. get: function () {
  11103. return this._stencilOpStencilDepthPass;
  11104. },
  11105. set: function (value) {
  11106. if (this._stencilOpStencilDepthPass === value) {
  11107. return;
  11108. }
  11109. this._stencilOpStencilDepthPass = value;
  11110. this._isStencilOpDirty = true;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11116. get: function () {
  11117. return this._stencilMask;
  11118. },
  11119. set: function (value) {
  11120. if (this._stencilMask === value) {
  11121. return;
  11122. }
  11123. this._stencilMask = value;
  11124. this._isStencilMaskDirty = true;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11130. get: function () {
  11131. return this._stencilTest;
  11132. },
  11133. set: function (value) {
  11134. if (this._stencilTest === value) {
  11135. return;
  11136. }
  11137. this._stencilTest = value;
  11138. this._isStencilTestDirty = true;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. _StencilState.prototype.reset = function () {
  11144. this._stencilTest = false;
  11145. this._stencilMask = 0xFF;
  11146. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11147. this._stencilFuncRef = 1;
  11148. this._stencilFuncMask = 0xFF;
  11149. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11150. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11151. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11152. this._isStencilTestDirty = true;
  11153. this._isStencilMaskDirty = true;
  11154. this._isStencilFuncDirty = true;
  11155. this._isStencilOpDirty = true;
  11156. };
  11157. _StencilState.prototype.apply = function (gl) {
  11158. if (!this.isDirty) {
  11159. return;
  11160. }
  11161. // Stencil test
  11162. if (this._isStencilTestDirty) {
  11163. if (this.stencilTest) {
  11164. gl.enable(gl.STENCIL_TEST);
  11165. }
  11166. else {
  11167. gl.disable(gl.STENCIL_TEST);
  11168. }
  11169. this._isStencilTestDirty = false;
  11170. }
  11171. // Stencil mask
  11172. if (this._isStencilMaskDirty) {
  11173. gl.stencilMask(this.stencilMask);
  11174. this._isStencilMaskDirty = false;
  11175. }
  11176. // Stencil func
  11177. if (this._isStencilFuncDirty) {
  11178. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11179. this._isStencilFuncDirty = false;
  11180. }
  11181. // Stencil op
  11182. if (this._isStencilOpDirty) {
  11183. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11184. this._isStencilOpDirty = false;
  11185. }
  11186. };
  11187. return _StencilState;
  11188. }());
  11189. BABYLON._StencilState = _StencilState;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.stencilState.js.map
  11192. var __assign = (this && this.__assign) || function () {
  11193. __assign = Object.assign || function(t) {
  11194. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11195. s = arguments[i];
  11196. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11197. t[p] = s[p];
  11198. }
  11199. return t;
  11200. };
  11201. return __assign.apply(this, arguments);
  11202. };
  11203. var BABYLON;
  11204. (function (BABYLON) {
  11205. /**
  11206. * Keeps track of all the buffer info used in engine.
  11207. */
  11208. var BufferPointer = /** @class */ (function () {
  11209. function BufferPointer() {
  11210. }
  11211. return BufferPointer;
  11212. }());
  11213. /**
  11214. * Interface for attribute information associated with buffer instanciation
  11215. */
  11216. var InstancingAttributeInfo = /** @class */ (function () {
  11217. function InstancingAttributeInfo() {
  11218. }
  11219. return InstancingAttributeInfo;
  11220. }());
  11221. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11222. /**
  11223. * Define options used to create a render target texture
  11224. */
  11225. var RenderTargetCreationOptions = /** @class */ (function () {
  11226. function RenderTargetCreationOptions() {
  11227. }
  11228. return RenderTargetCreationOptions;
  11229. }());
  11230. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11231. /**
  11232. * Define options used to create a depth texture
  11233. */
  11234. var DepthTextureCreationOptions = /** @class */ (function () {
  11235. function DepthTextureCreationOptions() {
  11236. }
  11237. return DepthTextureCreationOptions;
  11238. }());
  11239. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11240. /**
  11241. * Class used to describe the capabilities of the engine relatively to the current browser
  11242. */
  11243. var EngineCapabilities = /** @class */ (function () {
  11244. function EngineCapabilities() {
  11245. }
  11246. return EngineCapabilities;
  11247. }());
  11248. BABYLON.EngineCapabilities = EngineCapabilities;
  11249. /**
  11250. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11251. */
  11252. var Engine = /** @class */ (function () {
  11253. /**
  11254. * Creates a new engine
  11255. * @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
  11256. * @param antialias defines enable antialiasing (default: false)
  11257. * @param options defines further options to be sent to the getContext() function
  11258. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11259. */
  11260. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11261. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11262. var _this = this;
  11263. // Public members
  11264. /**
  11265. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11266. */
  11267. this.forcePOTTextures = false;
  11268. /**
  11269. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11270. */
  11271. this.isFullscreen = false;
  11272. /**
  11273. * Gets a boolean indicating if the pointer is currently locked
  11274. */
  11275. this.isPointerLock = false;
  11276. /**
  11277. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11278. */
  11279. this.cullBackFaces = true;
  11280. /**
  11281. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11282. */
  11283. this.renderEvenInBackground = true;
  11284. /**
  11285. * Gets or sets a boolean indicating that cache can be kept between frames
  11286. */
  11287. this.preventCacheWipeBetweenFrames = false;
  11288. /**
  11289. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11290. **/
  11291. this.enableOfflineSupport = false;
  11292. /**
  11293. * 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)
  11294. **/
  11295. this.disableManifestCheck = false;
  11296. /**
  11297. * Gets the list of created scenes
  11298. */
  11299. this.scenes = new Array();
  11300. /**
  11301. * Gets the list of created postprocesses
  11302. */
  11303. this.postProcesses = new Array();
  11304. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11305. this.validateShaderPrograms = false;
  11306. // Observables
  11307. /**
  11308. * Observable event triggered each time the rendering canvas is resized
  11309. */
  11310. this.onResizeObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable event triggered each time the canvas loses focus
  11313. */
  11314. this.onCanvasBlurObservable = new BABYLON.Observable();
  11315. /**
  11316. * Observable event triggered each time the canvas gains focus
  11317. */
  11318. this.onCanvasFocusObservable = new BABYLON.Observable();
  11319. /**
  11320. * Observable event triggered each time the canvas receives pointerout event
  11321. */
  11322. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11323. /**
  11324. * Observable event triggered before each texture is initialized
  11325. */
  11326. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11327. //WebVR
  11328. this._vrDisplay = undefined;
  11329. this._vrSupported = false;
  11330. this._vrExclusivePointerMode = false;
  11331. // Uniform buffers list
  11332. /**
  11333. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11334. */
  11335. this.disableUniformBuffers = false;
  11336. /** @hidden */
  11337. this._uniformBuffers = new Array();
  11338. // Observables
  11339. /**
  11340. * Observable raised when the engine begins a new frame
  11341. */
  11342. this.onBeginFrameObservable = new BABYLON.Observable();
  11343. /**
  11344. * Observable raised when the engine ends the current frame
  11345. */
  11346. this.onEndFrameObservable = new BABYLON.Observable();
  11347. /**
  11348. * Observable raised when the engine is about to compile a shader
  11349. */
  11350. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11351. /**
  11352. * Observable raised when the engine has jsut compiled a shader
  11353. */
  11354. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11355. this._windowIsBackground = false;
  11356. this._webGLVersion = 1.0;
  11357. /** @hidden */
  11358. this._badOS = false;
  11359. /** @hidden */
  11360. this._badDesktopOS = false;
  11361. /**
  11362. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11363. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11364. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11365. */
  11366. this.disableTextureBindingOptimization = false;
  11367. /**
  11368. * Observable signaled when VR display mode changes
  11369. */
  11370. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11371. /**
  11372. * Observable signaled when VR request present is complete
  11373. */
  11374. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11375. /**
  11376. * Observable signaled when VR request present starts
  11377. */
  11378. this.onVRRequestPresentStart = new BABYLON.Observable();
  11379. this._colorWrite = true;
  11380. /** @hidden */
  11381. this._drawCalls = new BABYLON.PerfCounter();
  11382. /** @hidden */
  11383. this._textureCollisions = new BABYLON.PerfCounter();
  11384. this._renderingQueueLaunched = false;
  11385. this._activeRenderLoops = new Array();
  11386. // Deterministic lockstepMaxSteps
  11387. this._deterministicLockstep = false;
  11388. this._lockstepMaxSteps = 4;
  11389. // Lost context
  11390. /**
  11391. * Observable signaled when a context lost event is raised
  11392. */
  11393. this.onContextLostObservable = new BABYLON.Observable();
  11394. /**
  11395. * Observable signaled when a context restored event is raised
  11396. */
  11397. this.onContextRestoredObservable = new BABYLON.Observable();
  11398. this._contextWasLost = false;
  11399. this._doNotHandleContextLost = false;
  11400. // FPS
  11401. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11402. this._fps = 60;
  11403. this._deltaTime = 0;
  11404. /**
  11405. * Turn this value on if you want to pause FPS computation when in background
  11406. */
  11407. this.disablePerformanceMonitorInBackground = false;
  11408. // States
  11409. /** @hidden */
  11410. this._depthCullingState = new BABYLON._DepthCullingState();
  11411. /** @hidden */
  11412. this._stencilState = new BABYLON._StencilState();
  11413. /** @hidden */
  11414. this._alphaState = new BABYLON._AlphaState();
  11415. /** @hidden */
  11416. this._alphaMode = Engine.ALPHA_DISABLE;
  11417. // Cache
  11418. this._internalTexturesCache = new Array();
  11419. /** @hidden */
  11420. this._activeChannel = 0;
  11421. this._currentTextureChannel = -1;
  11422. /** @hidden */
  11423. this._boundTexturesCache = {};
  11424. this._compiledEffects = {};
  11425. this._vertexAttribArraysEnabled = [];
  11426. this._uintIndicesCurrentlySet = false;
  11427. this._currentBoundBuffer = new Array();
  11428. /** @hidden */
  11429. this._currentFramebuffer = null;
  11430. this._currentBufferPointers = new Array();
  11431. this._currentInstanceLocations = new Array();
  11432. this._currentInstanceBuffers = new Array();
  11433. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11434. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11435. this._vaoRecordInProgress = false;
  11436. this._mustWipeVertexAttributes = false;
  11437. this._nextFreeTextureSlots = new Array();
  11438. this._maxSimultaneousTextures = 0;
  11439. this._activeRequests = new Array();
  11440. // Hardware supported Compressed Textures
  11441. this._texturesSupported = new Array();
  11442. /**
  11443. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11444. */
  11445. this.premultipliedAlpha = true;
  11446. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11447. this._onVRFullScreenTriggered = function () {
  11448. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11449. //get the old size before we change
  11450. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11451. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11452. //get the width and height, change the render size
  11453. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11454. _this.setHardwareScalingLevel(1);
  11455. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11456. }
  11457. else {
  11458. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11459. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11460. }
  11461. };
  11462. this._unpackFlipYCached = null;
  11463. this._boundUniforms = {};
  11464. // Register promises
  11465. BABYLON.PromisePolyfill.Apply();
  11466. var canvas = null;
  11467. Engine.Instances.push(this);
  11468. if (!canvasOrContext) {
  11469. return;
  11470. }
  11471. options = options || {};
  11472. if (canvasOrContext.getContext) {
  11473. canvas = canvasOrContext;
  11474. this._renderingCanvas = canvas;
  11475. if (antialias != null) {
  11476. options.antialias = antialias;
  11477. }
  11478. if (options.deterministicLockstep === undefined) {
  11479. options.deterministicLockstep = false;
  11480. }
  11481. if (options.lockstepMaxSteps === undefined) {
  11482. options.lockstepMaxSteps = 4;
  11483. }
  11484. if (options.preserveDrawingBuffer === undefined) {
  11485. options.preserveDrawingBuffer = false;
  11486. }
  11487. if (options.audioEngine === undefined) {
  11488. options.audioEngine = true;
  11489. }
  11490. if (options.stencil === undefined) {
  11491. options.stencil = true;
  11492. }
  11493. if (options.premultipliedAlpha === false) {
  11494. this.premultipliedAlpha = false;
  11495. }
  11496. this._deterministicLockstep = options.deterministicLockstep;
  11497. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11498. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11499. // Exceptions
  11500. if (navigator && navigator.userAgent) {
  11501. var ua = navigator.userAgent;
  11502. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11503. var exception = _a[_i];
  11504. var key = exception.key;
  11505. var targets = exception.targets;
  11506. if (ua.indexOf(key) > -1) {
  11507. if (exception.capture && exception.captureConstraint) {
  11508. var capture = exception.capture;
  11509. var constraint = exception.captureConstraint;
  11510. var regex = new RegExp(capture);
  11511. var matches = regex.exec(ua);
  11512. if (matches && matches.length > 0) {
  11513. var capturedValue = parseInt(matches[matches.length - 1]);
  11514. if (capturedValue >= constraint) {
  11515. continue;
  11516. }
  11517. }
  11518. }
  11519. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11520. var target = targets_1[_b];
  11521. switch (target) {
  11522. case "uniformBuffer":
  11523. this.disableUniformBuffers = true;
  11524. break;
  11525. case "textureBindingOptimization":
  11526. this.disableTextureBindingOptimization = true;
  11527. break;
  11528. }
  11529. }
  11530. }
  11531. }
  11532. }
  11533. // GL
  11534. if (!options.disableWebGL2Support) {
  11535. try {
  11536. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11537. if (this._gl) {
  11538. this._webGLVersion = 2.0;
  11539. }
  11540. }
  11541. catch (e) {
  11542. // Do nothing
  11543. }
  11544. }
  11545. if (!this._gl) {
  11546. if (!canvas) {
  11547. throw new Error("The provided canvas is null or undefined.");
  11548. }
  11549. try {
  11550. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11551. }
  11552. catch (e) {
  11553. throw new Error("WebGL not supported");
  11554. }
  11555. }
  11556. if (!this._gl) {
  11557. throw new Error("WebGL not supported");
  11558. }
  11559. this._onCanvasFocus = function () {
  11560. _this.onCanvasFocusObservable.notifyObservers(_this);
  11561. };
  11562. this._onCanvasBlur = function () {
  11563. _this.onCanvasBlurObservable.notifyObservers(_this);
  11564. };
  11565. canvas.addEventListener("focus", this._onCanvasFocus);
  11566. canvas.addEventListener("blur", this._onCanvasBlur);
  11567. this._onBlur = function () {
  11568. if (_this.disablePerformanceMonitorInBackground) {
  11569. _this._performanceMonitor.disable();
  11570. }
  11571. _this._windowIsBackground = true;
  11572. };
  11573. this._onFocus = function () {
  11574. if (_this.disablePerformanceMonitorInBackground) {
  11575. _this._performanceMonitor.enable();
  11576. }
  11577. _this._windowIsBackground = false;
  11578. };
  11579. this._onCanvasPointerOut = function (ev) {
  11580. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11581. };
  11582. window.addEventListener("blur", this._onBlur);
  11583. window.addEventListener("focus", this._onFocus);
  11584. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11585. // Context lost
  11586. if (!this._doNotHandleContextLost) {
  11587. this._onContextLost = function (evt) {
  11588. evt.preventDefault();
  11589. _this._contextWasLost = true;
  11590. BABYLON.Tools.Warn("WebGL context lost.");
  11591. _this.onContextLostObservable.notifyObservers(_this);
  11592. };
  11593. this._onContextRestored = function (evt) {
  11594. // Adding a timeout to avoid race condition at browser level
  11595. setTimeout(function () {
  11596. // Rebuild gl context
  11597. _this._initGLContext();
  11598. // Rebuild effects
  11599. _this._rebuildEffects();
  11600. // Rebuild textures
  11601. _this._rebuildInternalTextures();
  11602. // Rebuild buffers
  11603. _this._rebuildBuffers();
  11604. // Cache
  11605. _this.wipeCaches(true);
  11606. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11607. _this.onContextRestoredObservable.notifyObservers(_this);
  11608. _this._contextWasLost = false;
  11609. }, 0);
  11610. };
  11611. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11612. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11613. }
  11614. }
  11615. else {
  11616. this._gl = canvasOrContext;
  11617. this._renderingCanvas = this._gl.canvas;
  11618. if (this._gl.renderbufferStorageMultisample) {
  11619. this._webGLVersion = 2.0;
  11620. }
  11621. options.stencil = this._gl.getContextAttributes().stencil;
  11622. }
  11623. // Viewport
  11624. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11625. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11626. this.resize();
  11627. this._isStencilEnable = options.stencil ? true : false;
  11628. this._initGLContext();
  11629. if (canvas) {
  11630. // Fullscreen
  11631. this._onFullscreenChange = function () {
  11632. if (document.fullscreen !== undefined) {
  11633. _this.isFullscreen = document.fullscreen;
  11634. }
  11635. else if (document.mozFullScreen !== undefined) {
  11636. _this.isFullscreen = document.mozFullScreen;
  11637. }
  11638. else if (document.webkitIsFullScreen !== undefined) {
  11639. _this.isFullscreen = document.webkitIsFullScreen;
  11640. }
  11641. else if (document.msIsFullScreen !== undefined) {
  11642. _this.isFullscreen = document.msIsFullScreen;
  11643. }
  11644. // Pointer lock
  11645. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11646. canvas.requestPointerLock = canvas.requestPointerLock ||
  11647. canvas.msRequestPointerLock ||
  11648. canvas.mozRequestPointerLock ||
  11649. canvas.webkitRequestPointerLock;
  11650. if (canvas.requestPointerLock) {
  11651. canvas.requestPointerLock();
  11652. }
  11653. }
  11654. };
  11655. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11656. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11657. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11658. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11659. // Pointer lock
  11660. this._onPointerLockChange = function () {
  11661. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11662. document.webkitPointerLockElement === canvas ||
  11663. document.msPointerLockElement === canvas ||
  11664. document.pointerLockElement === canvas);
  11665. };
  11666. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11667. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11668. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11669. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11670. this._onVRDisplayPointerRestricted = function () {
  11671. if (canvas) {
  11672. canvas.requestPointerLock();
  11673. }
  11674. };
  11675. this._onVRDisplayPointerUnrestricted = function () {
  11676. document.exitPointerLock();
  11677. };
  11678. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11679. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11680. }
  11681. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11682. Engine.audioEngine = new BABYLON.AudioEngine();
  11683. }
  11684. // Prepare buffer pointers
  11685. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11686. this._currentBufferPointers[i] = new BufferPointer();
  11687. }
  11688. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11689. // Load WebVR Devices
  11690. if (options.autoEnableWebVR) {
  11691. this.initWebVR();
  11692. }
  11693. // Detect if we are running on a faulty buggy OS.
  11694. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11695. // Detect if we are running on a faulty buggy desktop OS.
  11696. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11697. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11698. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11699. }
  11700. Object.defineProperty(Engine, "LastCreatedEngine", {
  11701. /**
  11702. * Gets the latest created engine
  11703. */
  11704. get: function () {
  11705. if (Engine.Instances.length === 0) {
  11706. return null;
  11707. }
  11708. return Engine.Instances[Engine.Instances.length - 1];
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine, "LastCreatedScene", {
  11714. /**
  11715. * Gets the latest created scene
  11716. */
  11717. get: function () {
  11718. var lastCreatedEngine = Engine.LastCreatedEngine;
  11719. if (!lastCreatedEngine) {
  11720. return null;
  11721. }
  11722. if (lastCreatedEngine.scenes.length === 0) {
  11723. return null;
  11724. }
  11725. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. /**
  11731. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11732. * @param flag defines which part of the materials must be marked as dirty
  11733. * @param predicate defines a predicate used to filter which materials should be affected
  11734. */
  11735. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11736. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11737. var engine = Engine.Instances[engineIndex];
  11738. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11739. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11740. }
  11741. }
  11742. };
  11743. Object.defineProperty(Engine, "Version", {
  11744. /**
  11745. * Returns the current version of the framework
  11746. */
  11747. get: function () {
  11748. return "3.3.0-beta.2";
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11754. /**
  11755. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11756. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11757. */
  11758. get: function () {
  11759. return this._vrExclusivePointerMode;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11765. /**
  11766. * Gets a boolean indicating that the engine supports uniform buffers
  11767. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11768. */
  11769. get: function () {
  11770. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11776. /**
  11777. * Gets a boolean indicating that only power of 2 textures are supported
  11778. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11779. */
  11780. get: function () {
  11781. return this._webGLVersion < 2 || this.forcePOTTextures;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11787. /**
  11788. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11789. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11790. */
  11791. get: function () {
  11792. return this._doNotHandleContextLost;
  11793. },
  11794. set: function (value) {
  11795. this._doNotHandleContextLost = value;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11801. /**
  11802. * Gets the performance monitor attached to this engine
  11803. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11804. */
  11805. get: function () {
  11806. return this._performanceMonitor;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11812. /**
  11813. * Gets the list of texture formats supported
  11814. */
  11815. get: function () {
  11816. return this._texturesSupported;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11822. /**
  11823. * Gets the list of texture formats in use
  11824. */
  11825. get: function () {
  11826. return this._textureFormatInUse;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine.prototype, "currentViewport", {
  11832. /**
  11833. * Gets the current viewport
  11834. */
  11835. get: function () {
  11836. return this._cachedViewport;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11842. /**
  11843. * Gets the default empty texture
  11844. */
  11845. get: function () {
  11846. if (!this._emptyTexture) {
  11847. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11848. }
  11849. return this._emptyTexture;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11855. /**
  11856. * Gets the default empty 3D texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyTexture3D) {
  11860. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11861. }
  11862. return this._emptyTexture3D;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11868. /**
  11869. * Gets the default empty cube texture
  11870. */
  11871. get: function () {
  11872. if (!this._emptyCubeTexture) {
  11873. var faceData = new Uint8Array(4);
  11874. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11875. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11876. }
  11877. return this._emptyCubeTexture;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Engine.prototype._rebuildInternalTextures = function () {
  11883. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11884. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11885. var internalTexture = currentState_1[_i];
  11886. internalTexture._rebuild();
  11887. }
  11888. };
  11889. Engine.prototype._rebuildEffects = function () {
  11890. for (var key in this._compiledEffects) {
  11891. var effect = this._compiledEffects[key];
  11892. effect._prepareEffect();
  11893. }
  11894. BABYLON.Effect.ResetCache();
  11895. };
  11896. Engine.prototype._rebuildBuffers = function () {
  11897. // Index / Vertex
  11898. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11899. var scene = _a[_i];
  11900. scene.resetCachedMaterial();
  11901. scene._rebuildGeometries();
  11902. scene._rebuildTextures();
  11903. }
  11904. // Uniforms
  11905. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11906. var uniformBuffer = _c[_b];
  11907. uniformBuffer._rebuild();
  11908. }
  11909. };
  11910. Engine.prototype._initGLContext = function () {
  11911. // Caps
  11912. this._caps = new EngineCapabilities();
  11913. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11914. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11915. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11916. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11917. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11918. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11919. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11920. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11921. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11922. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11923. // Infos
  11924. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11925. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11926. if (rendererInfo != null) {
  11927. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11928. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11929. }
  11930. if (!this._glVendor) {
  11931. this._glVendor = "Unknown vendor";
  11932. }
  11933. if (!this._glRenderer) {
  11934. this._glRenderer = "Unknown renderer";
  11935. }
  11936. // Constants
  11937. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11938. if (this._gl.RGBA16F !== 0x881A) {
  11939. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11940. }
  11941. if (this._gl.RGBA32F !== 0x8814) {
  11942. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11943. }
  11944. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11945. this._gl.DEPTH24_STENCIL8 = 35056;
  11946. }
  11947. // Extensions
  11948. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11949. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11950. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11951. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11952. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11953. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11954. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11955. 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');
  11956. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11957. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11958. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11959. this._caps.highPrecisionShaderSupported = true;
  11960. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11961. if (this._caps.timerQuery) {
  11962. if (this._webGLVersion === 1) {
  11963. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11964. }
  11965. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11966. }
  11967. // Checks if some of the format renders first to allow the use of webgl inspector.
  11968. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11969. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11970. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11971. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11972. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11973. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11974. if (this._webGLVersion > 1) {
  11975. this._gl.HALF_FLOAT_OES = 0x140B;
  11976. }
  11977. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11978. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11979. // Draw buffers
  11980. if (this._webGLVersion > 1) {
  11981. this._caps.drawBuffersExtension = true;
  11982. }
  11983. else {
  11984. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11985. if (drawBuffersExtension !== null) {
  11986. this._caps.drawBuffersExtension = true;
  11987. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11988. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11989. for (var i = 0; i < 16; i++) {
  11990. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11991. }
  11992. }
  11993. else {
  11994. this._caps.drawBuffersExtension = false;
  11995. }
  11996. }
  11997. // Depth Texture
  11998. if (this._webGLVersion > 1) {
  11999. this._caps.depthTextureExtension = true;
  12000. }
  12001. else {
  12002. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12003. if (depthTextureExtension != null) {
  12004. this._caps.depthTextureExtension = true;
  12005. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12006. }
  12007. }
  12008. // Vertex array object
  12009. if (this._webGLVersion > 1) {
  12010. this._caps.vertexArrayObject = true;
  12011. }
  12012. else {
  12013. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12014. if (vertexArrayObjectExtension != null) {
  12015. this._caps.vertexArrayObject = true;
  12016. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12017. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12018. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12019. }
  12020. else {
  12021. this._caps.vertexArrayObject = false;
  12022. }
  12023. }
  12024. // Instances count
  12025. if (this._webGLVersion > 1) {
  12026. this._caps.instancedArrays = true;
  12027. }
  12028. else {
  12029. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12030. if (instanceExtension != null) {
  12031. this._caps.instancedArrays = true;
  12032. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12033. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12034. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12035. }
  12036. else {
  12037. this._caps.instancedArrays = false;
  12038. }
  12039. }
  12040. // Intelligently add supported compressed formats in order to check for.
  12041. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12042. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12043. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12044. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12045. if (this._caps.astc)
  12046. this.texturesSupported.push('-astc.ktx');
  12047. if (this._caps.s3tc)
  12048. this.texturesSupported.push('-dxt.ktx');
  12049. if (this._caps.pvrtc)
  12050. this.texturesSupported.push('-pvrtc.ktx');
  12051. if (this._caps.etc2)
  12052. this.texturesSupported.push('-etc2.ktx');
  12053. if (this._caps.etc1)
  12054. this.texturesSupported.push('-etc1.ktx');
  12055. if (this._gl.getShaderPrecisionFormat) {
  12056. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12057. if (highp) {
  12058. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12059. }
  12060. }
  12061. // Depth buffer
  12062. this.setDepthBuffer(true);
  12063. this.setDepthFunctionToLessOrEqual();
  12064. this.setDepthWrite(true);
  12065. // Texture maps
  12066. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12067. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12068. this._nextFreeTextureSlots.push(slot);
  12069. }
  12070. };
  12071. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12072. /**
  12073. * Gets version of the current webGL context
  12074. */
  12075. get: function () {
  12076. return this._webGLVersion;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12082. /**
  12083. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12084. */
  12085. get: function () {
  12086. return this._isStencilEnable;
  12087. },
  12088. enumerable: true,
  12089. configurable: true
  12090. });
  12091. Engine.prototype._prepareWorkingCanvas = function () {
  12092. if (this._workingCanvas) {
  12093. return;
  12094. }
  12095. this._workingCanvas = document.createElement("canvas");
  12096. var context = this._workingCanvas.getContext("2d");
  12097. if (context) {
  12098. this._workingContext = context;
  12099. }
  12100. };
  12101. /**
  12102. * Reset the texture cache to empty state
  12103. */
  12104. Engine.prototype.resetTextureCache = function () {
  12105. for (var key in this._boundTexturesCache) {
  12106. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12107. continue;
  12108. }
  12109. var boundTexture = this._boundTexturesCache[key];
  12110. if (boundTexture) {
  12111. this._removeDesignatedSlot(boundTexture);
  12112. }
  12113. this._boundTexturesCache[key] = null;
  12114. }
  12115. if (!this.disableTextureBindingOptimization) {
  12116. this._nextFreeTextureSlots = [];
  12117. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12118. this._nextFreeTextureSlots.push(slot);
  12119. }
  12120. }
  12121. this._currentTextureChannel = -1;
  12122. };
  12123. /**
  12124. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12125. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12126. * @returns true if engine is in deterministic lock step mode
  12127. */
  12128. Engine.prototype.isDeterministicLockStep = function () {
  12129. return this._deterministicLockstep;
  12130. };
  12131. /**
  12132. * Gets the max steps when engine is running in deterministic lock step
  12133. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12134. * @returns the max steps
  12135. */
  12136. Engine.prototype.getLockstepMaxSteps = function () {
  12137. return this._lockstepMaxSteps;
  12138. };
  12139. /**
  12140. * Gets an object containing information about the current webGL context
  12141. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12142. */
  12143. Engine.prototype.getGlInfo = function () {
  12144. return {
  12145. vendor: this._glVendor,
  12146. renderer: this._glRenderer,
  12147. version: this._glVersion
  12148. };
  12149. };
  12150. /**
  12151. * Gets current aspect ratio
  12152. * @param camera defines the camera to use to get the aspect ratio
  12153. * @param useScreen defines if screen size must be used (or the current render target if any)
  12154. * @returns a number defining the aspect ratio
  12155. */
  12156. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12157. if (useScreen === void 0) { useScreen = false; }
  12158. var viewport = camera.viewport;
  12159. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12160. };
  12161. /**
  12162. * Gets current screen aspect ratio
  12163. * @returns a number defining the aspect ratio
  12164. */
  12165. Engine.prototype.getScreenAspectRatio = function () {
  12166. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12167. };
  12168. /**
  12169. * Gets the current render width
  12170. * @param useScreen defines if screen size must be used (or the current render target if any)
  12171. * @returns a number defining the current render width
  12172. */
  12173. Engine.prototype.getRenderWidth = function (useScreen) {
  12174. if (useScreen === void 0) { useScreen = false; }
  12175. if (!useScreen && this._currentRenderTarget) {
  12176. return this._currentRenderTarget.width;
  12177. }
  12178. return this._gl.drawingBufferWidth;
  12179. };
  12180. /**
  12181. * Gets the current render height
  12182. * @param useScreen defines if screen size must be used (or the current render target if any)
  12183. * @returns a number defining the current render height
  12184. */
  12185. Engine.prototype.getRenderHeight = function (useScreen) {
  12186. if (useScreen === void 0) { useScreen = false; }
  12187. if (!useScreen && this._currentRenderTarget) {
  12188. return this._currentRenderTarget.height;
  12189. }
  12190. return this._gl.drawingBufferHeight;
  12191. };
  12192. /**
  12193. * Gets the HTML canvas attached with the current webGL context
  12194. * @returns a HTML canvas
  12195. */
  12196. Engine.prototype.getRenderingCanvas = function () {
  12197. return this._renderingCanvas;
  12198. };
  12199. /**
  12200. * Gets the client rect of the HTML canvas attached with the current webGL context
  12201. * @returns a client rectanglee
  12202. */
  12203. Engine.prototype.getRenderingCanvasClientRect = function () {
  12204. if (!this._renderingCanvas) {
  12205. return null;
  12206. }
  12207. return this._renderingCanvas.getBoundingClientRect();
  12208. };
  12209. /**
  12210. * Defines the hardware scaling level.
  12211. * By default the hardware scaling level is computed from the window device ratio.
  12212. * 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.
  12213. * @param level defines the level to use
  12214. */
  12215. Engine.prototype.setHardwareScalingLevel = function (level) {
  12216. this._hardwareScalingLevel = level;
  12217. this.resize();
  12218. };
  12219. /**
  12220. * Gets the current hardware scaling level.
  12221. * By default the hardware scaling level is computed from the window device ratio.
  12222. * 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.
  12223. * @returns a number indicating the current hardware scaling level
  12224. */
  12225. Engine.prototype.getHardwareScalingLevel = function () {
  12226. return this._hardwareScalingLevel;
  12227. };
  12228. /**
  12229. * Gets the list of loaded textures
  12230. * @returns an array containing all loaded textures
  12231. */
  12232. Engine.prototype.getLoadedTexturesCache = function () {
  12233. return this._internalTexturesCache;
  12234. };
  12235. /**
  12236. * Gets the object containing all engine capabilities
  12237. * @returns the EngineCapabilities object
  12238. */
  12239. Engine.prototype.getCaps = function () {
  12240. return this._caps;
  12241. };
  12242. Object.defineProperty(Engine.prototype, "drawCalls", {
  12243. /** @hidden */
  12244. get: function () {
  12245. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12246. return 0;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12252. /** @hidden */
  12253. get: function () {
  12254. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12255. return null;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. /**
  12261. * Gets the current depth function
  12262. * @returns a number defining the depth function
  12263. */
  12264. Engine.prototype.getDepthFunction = function () {
  12265. return this._depthCullingState.depthFunc;
  12266. };
  12267. /**
  12268. * Sets the current depth function
  12269. * @param depthFunc defines the function to use
  12270. */
  12271. Engine.prototype.setDepthFunction = function (depthFunc) {
  12272. this._depthCullingState.depthFunc = depthFunc;
  12273. };
  12274. /**
  12275. * Sets the current depth function to GREATER
  12276. */
  12277. Engine.prototype.setDepthFunctionToGreater = function () {
  12278. this._depthCullingState.depthFunc = this._gl.GREATER;
  12279. };
  12280. /**
  12281. * Sets the current depth function to GEQUAL
  12282. */
  12283. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12284. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12285. };
  12286. /**
  12287. * Sets the current depth function to LESS
  12288. */
  12289. Engine.prototype.setDepthFunctionToLess = function () {
  12290. this._depthCullingState.depthFunc = this._gl.LESS;
  12291. };
  12292. /**
  12293. * Sets the current depth function to LEQUAL
  12294. */
  12295. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12296. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12297. };
  12298. /**
  12299. * Gets a boolean indicating if stencil buffer is enabled
  12300. * @returns the current stencil buffer state
  12301. */
  12302. Engine.prototype.getStencilBuffer = function () {
  12303. return this._stencilState.stencilTest;
  12304. };
  12305. /**
  12306. * Enable or disable the stencil buffer
  12307. * @param enable defines if the stencil buffer must be enabled or disabled
  12308. */
  12309. Engine.prototype.setStencilBuffer = function (enable) {
  12310. this._stencilState.stencilTest = enable;
  12311. };
  12312. /**
  12313. * Gets the current stencil mask
  12314. * @returns a number defining the new stencil mask to use
  12315. */
  12316. Engine.prototype.getStencilMask = function () {
  12317. return this._stencilState.stencilMask;
  12318. };
  12319. /**
  12320. * Sets the current stencil mask
  12321. * @param mask defines the new stencil mask to use
  12322. */
  12323. Engine.prototype.setStencilMask = function (mask) {
  12324. this._stencilState.stencilMask = mask;
  12325. };
  12326. /**
  12327. * Gets the current stencil function
  12328. * @returns a number defining the stencil function to use
  12329. */
  12330. Engine.prototype.getStencilFunction = function () {
  12331. return this._stencilState.stencilFunc;
  12332. };
  12333. /**
  12334. * Gets the current stencil reference value
  12335. * @returns a number defining the stencil reference value to use
  12336. */
  12337. Engine.prototype.getStencilFunctionReference = function () {
  12338. return this._stencilState.stencilFuncRef;
  12339. };
  12340. /**
  12341. * Gets the current stencil mask
  12342. * @returns a number defining the stencil mask to use
  12343. */
  12344. Engine.prototype.getStencilFunctionMask = function () {
  12345. return this._stencilState.stencilFuncMask;
  12346. };
  12347. /**
  12348. * Sets the current stencil function
  12349. * @param stencilFunc defines the new stencil function to use
  12350. */
  12351. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12352. this._stencilState.stencilFunc = stencilFunc;
  12353. };
  12354. /**
  12355. * Sets the current stencil reference
  12356. * @param reference defines the new stencil reference to use
  12357. */
  12358. Engine.prototype.setStencilFunctionReference = function (reference) {
  12359. this._stencilState.stencilFuncRef = reference;
  12360. };
  12361. /**
  12362. * Sets the current stencil mask
  12363. * @param mask defines the new stencil mask to use
  12364. */
  12365. Engine.prototype.setStencilFunctionMask = function (mask) {
  12366. this._stencilState.stencilFuncMask = mask;
  12367. };
  12368. /**
  12369. * Gets the current stencil operation when stencil fails
  12370. * @returns a number defining stencil operation to use when stencil fails
  12371. */
  12372. Engine.prototype.getStencilOperationFail = function () {
  12373. return this._stencilState.stencilOpStencilFail;
  12374. };
  12375. /**
  12376. * Gets the current stencil operation when depth fails
  12377. * @returns a number defining stencil operation to use when depth fails
  12378. */
  12379. Engine.prototype.getStencilOperationDepthFail = function () {
  12380. return this._stencilState.stencilOpDepthFail;
  12381. };
  12382. /**
  12383. * Gets the current stencil operation when stencil passes
  12384. * @returns a number defining stencil operation to use when stencil passes
  12385. */
  12386. Engine.prototype.getStencilOperationPass = function () {
  12387. return this._stencilState.stencilOpStencilDepthPass;
  12388. };
  12389. /**
  12390. * Sets the stencil operation to use when stencil fails
  12391. * @param operation defines the stencil operation to use when stencil fails
  12392. */
  12393. Engine.prototype.setStencilOperationFail = function (operation) {
  12394. this._stencilState.stencilOpStencilFail = operation;
  12395. };
  12396. /**
  12397. * Sets the stencil operation to use when depth fails
  12398. * @param operation defines the stencil operation to use when depth fails
  12399. */
  12400. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12401. this._stencilState.stencilOpDepthFail = operation;
  12402. };
  12403. /**
  12404. * Sets the stencil operation to use when stencil passes
  12405. * @param operation defines the stencil operation to use when stencil passes
  12406. */
  12407. Engine.prototype.setStencilOperationPass = function (operation) {
  12408. this._stencilState.stencilOpStencilDepthPass = operation;
  12409. };
  12410. /**
  12411. * Sets a boolean indicating if the dithering state is enabled or disabled
  12412. * @param value defines the dithering state
  12413. */
  12414. Engine.prototype.setDitheringState = function (value) {
  12415. if (value) {
  12416. this._gl.enable(this._gl.DITHER);
  12417. }
  12418. else {
  12419. this._gl.disable(this._gl.DITHER);
  12420. }
  12421. };
  12422. /**
  12423. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12424. * @param value defines the rasterizer state
  12425. */
  12426. Engine.prototype.setRasterizerState = function (value) {
  12427. if (value) {
  12428. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12429. }
  12430. else {
  12431. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12432. }
  12433. };
  12434. /**
  12435. * stop executing a render loop function and remove it from the execution array
  12436. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12437. */
  12438. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12439. if (!renderFunction) {
  12440. this._activeRenderLoops = [];
  12441. return;
  12442. }
  12443. var index = this._activeRenderLoops.indexOf(renderFunction);
  12444. if (index >= 0) {
  12445. this._activeRenderLoops.splice(index, 1);
  12446. }
  12447. };
  12448. /** @hidden */
  12449. Engine.prototype._renderLoop = function () {
  12450. if (!this._contextWasLost) {
  12451. var shouldRender = true;
  12452. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12453. shouldRender = false;
  12454. }
  12455. if (shouldRender) {
  12456. // Start new frame
  12457. this.beginFrame();
  12458. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12459. var renderFunction = this._activeRenderLoops[index];
  12460. renderFunction();
  12461. }
  12462. // Present
  12463. this.endFrame();
  12464. }
  12465. }
  12466. if (this._activeRenderLoops.length > 0) {
  12467. // Register new frame
  12468. var requester = null;
  12469. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12470. requester = this._vrDisplay;
  12471. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12472. }
  12473. else {
  12474. this._renderingQueueLaunched = false;
  12475. }
  12476. };
  12477. /**
  12478. * Register and execute a render loop. The engine can have more than one render function
  12479. * @param renderFunction defines the function to continuously execute
  12480. */
  12481. Engine.prototype.runRenderLoop = function (renderFunction) {
  12482. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12483. return;
  12484. }
  12485. this._activeRenderLoops.push(renderFunction);
  12486. if (!this._renderingQueueLaunched) {
  12487. this._renderingQueueLaunched = true;
  12488. this._bindedRenderFunction = this._renderLoop.bind(this);
  12489. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12490. }
  12491. };
  12492. /**
  12493. * Toggle full screen mode
  12494. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12495. * @param options defines an option object to be sent to the requestFullscreen function
  12496. */
  12497. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12498. if (this.isFullscreen) {
  12499. BABYLON.Tools.ExitFullscreen();
  12500. }
  12501. else {
  12502. this._pointerLockRequested = requestPointerLock;
  12503. if (this._renderingCanvas) {
  12504. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12505. }
  12506. }
  12507. };
  12508. /**
  12509. * Clear the current render buffer or the current render target (if any is set up)
  12510. * @param color defines the color to use
  12511. * @param backBuffer defines if the back buffer must be cleared
  12512. * @param depth defines if the depth buffer must be cleared
  12513. * @param stencil defines if the stencil buffer must be cleared
  12514. */
  12515. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12516. if (stencil === void 0) { stencil = false; }
  12517. this.applyStates();
  12518. var mode = 0;
  12519. if (backBuffer && color) {
  12520. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12521. mode |= this._gl.COLOR_BUFFER_BIT;
  12522. }
  12523. if (depth) {
  12524. this._gl.clearDepth(1.0);
  12525. mode |= this._gl.DEPTH_BUFFER_BIT;
  12526. }
  12527. if (stencil) {
  12528. this._gl.clearStencil(0);
  12529. mode |= this._gl.STENCIL_BUFFER_BIT;
  12530. }
  12531. this._gl.clear(mode);
  12532. };
  12533. /**
  12534. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12535. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12536. * @param y defines the y-coordinate of the corner of the clear rectangle
  12537. * @param width defines the width of the clear rectangle
  12538. * @param height defines the height of the clear rectangle
  12539. * @param clearColor defines the clear color
  12540. */
  12541. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12542. var gl = this._gl;
  12543. // Save state
  12544. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12545. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12546. // Change state
  12547. gl.enable(gl.SCISSOR_TEST);
  12548. gl.scissor(x, y, width, height);
  12549. // Clear
  12550. this.clear(clearColor, true, true, true);
  12551. // Restore state
  12552. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12553. if (curScissor === true) {
  12554. gl.enable(gl.SCISSOR_TEST);
  12555. }
  12556. else {
  12557. gl.disable(gl.SCISSOR_TEST);
  12558. }
  12559. };
  12560. /** @hidden */
  12561. Engine.prototype._viewport = function (x, y, width, height) {
  12562. if (x !== this._viewportCached.x ||
  12563. y !== this._viewportCached.y ||
  12564. width !== this._viewportCached.z ||
  12565. height !== this._viewportCached.w) {
  12566. this._viewportCached.x = x;
  12567. this._viewportCached.y = y;
  12568. this._viewportCached.z = width;
  12569. this._viewportCached.w = height;
  12570. this._gl.viewport(x, y, width, height);
  12571. }
  12572. };
  12573. /**
  12574. * Set the WebGL's viewport
  12575. * @param viewport defines the viewport element to be used
  12576. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12577. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12578. */
  12579. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12580. var width = requiredWidth || this.getRenderWidth();
  12581. var height = requiredHeight || this.getRenderHeight();
  12582. var x = viewport.x || 0;
  12583. var y = viewport.y || 0;
  12584. this._cachedViewport = viewport;
  12585. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12586. };
  12587. /**
  12588. * Directly set the WebGL Viewport
  12589. * @param x defines the x coordinate of the viewport (in screen space)
  12590. * @param y defines the y coordinate of the viewport (in screen space)
  12591. * @param width defines the width of the viewport (in screen space)
  12592. * @param height defines the height of the viewport (in screen space)
  12593. * @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
  12594. */
  12595. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12596. var currentViewport = this._cachedViewport;
  12597. this._cachedViewport = null;
  12598. this._viewport(x, y, width, height);
  12599. return currentViewport;
  12600. };
  12601. /**
  12602. * Begin a new frame
  12603. */
  12604. Engine.prototype.beginFrame = function () {
  12605. this.onBeginFrameObservable.notifyObservers(this);
  12606. this._measureFps();
  12607. };
  12608. /**
  12609. * Enf the current frame
  12610. */
  12611. Engine.prototype.endFrame = function () {
  12612. // Force a flush in case we are using a bad OS.
  12613. if (this._badOS) {
  12614. this.flushFramebuffer();
  12615. }
  12616. // Submit frame to the vr device, if enabled
  12617. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12618. // TODO: We should only submit the frame if we read frameData successfully.
  12619. this._vrDisplay.submitFrame();
  12620. }
  12621. this.onEndFrameObservable.notifyObservers(this);
  12622. };
  12623. /**
  12624. * Resize the view according to the canvas' size
  12625. */
  12626. Engine.prototype.resize = function () {
  12627. // We're not resizing the size of the canvas while in VR mode & presenting
  12628. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12629. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12630. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12631. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12632. }
  12633. };
  12634. /**
  12635. * Force a specific size of the canvas
  12636. * @param width defines the new canvas' width
  12637. * @param height defines the new canvas' height
  12638. */
  12639. Engine.prototype.setSize = function (width, height) {
  12640. if (!this._renderingCanvas) {
  12641. return;
  12642. }
  12643. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12644. return;
  12645. }
  12646. this._renderingCanvas.width = width;
  12647. this._renderingCanvas.height = height;
  12648. for (var index = 0; index < this.scenes.length; index++) {
  12649. var scene = this.scenes[index];
  12650. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12651. var cam = scene.cameras[camIndex];
  12652. cam._currentRenderId = 0;
  12653. }
  12654. }
  12655. if (this.onResizeObservable.hasObservers) {
  12656. this.onResizeObservable.notifyObservers(this);
  12657. }
  12658. };
  12659. // WebVR functions
  12660. /**
  12661. * Gets a boolean indicating if a webVR device was detected
  12662. * @returns true if a webVR device was detected
  12663. */
  12664. Engine.prototype.isVRDevicePresent = function () {
  12665. return !!this._vrDisplay;
  12666. };
  12667. /**
  12668. * Gets the current webVR device
  12669. * @returns the current webVR device (or null)
  12670. */
  12671. Engine.prototype.getVRDevice = function () {
  12672. return this._vrDisplay;
  12673. };
  12674. /**
  12675. * Initializes a webVR display and starts listening to display change events
  12676. * The onVRDisplayChangedObservable will be notified upon these changes
  12677. * @returns The onVRDisplayChangedObservable
  12678. */
  12679. Engine.prototype.initWebVR = function () {
  12680. this.initWebVRAsync();
  12681. return this.onVRDisplayChangedObservable;
  12682. };
  12683. /**
  12684. * Initializes a webVR display and starts listening to display change events
  12685. * The onVRDisplayChangedObservable will be notified upon these changes
  12686. * @returns A promise containing a VRDisplay and if vr is supported
  12687. */
  12688. Engine.prototype.initWebVRAsync = function () {
  12689. var _this = this;
  12690. var notifyObservers = function () {
  12691. var eventArgs = {
  12692. vrDisplay: _this._vrDisplay,
  12693. vrSupported: _this._vrSupported
  12694. };
  12695. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12696. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12697. };
  12698. if (!this._onVrDisplayConnect) {
  12699. this._onVrDisplayConnect = function (event) {
  12700. _this._vrDisplay = event.display;
  12701. notifyObservers();
  12702. };
  12703. this._onVrDisplayDisconnect = function () {
  12704. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12705. _this._vrDisplay = undefined;
  12706. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12707. notifyObservers();
  12708. };
  12709. this._onVrDisplayPresentChange = function () {
  12710. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12711. };
  12712. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12713. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12714. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12715. }
  12716. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12717. this._webVRInitPromise.then(notifyObservers);
  12718. return this._webVRInitPromise;
  12719. };
  12720. /**
  12721. * Call this function to switch to webVR mode
  12722. * Will do nothing if webVR is not supported or if there is no webVR device
  12723. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12724. */
  12725. Engine.prototype.enableVR = function () {
  12726. var _this = this;
  12727. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12728. var onResolved = function () {
  12729. _this.onVRRequestPresentComplete.notifyObservers(true);
  12730. _this._onVRFullScreenTriggered();
  12731. };
  12732. var onRejected = function () {
  12733. _this.onVRRequestPresentComplete.notifyObservers(false);
  12734. };
  12735. this.onVRRequestPresentStart.notifyObservers(this);
  12736. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12737. }
  12738. };
  12739. /**
  12740. * Call this function to leave webVR mode
  12741. * Will do nothing if webVR is not supported or if there is no webVR device
  12742. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12743. */
  12744. Engine.prototype.disableVR = function () {
  12745. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12746. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12747. }
  12748. };
  12749. Engine.prototype._getVRDisplaysAsync = function () {
  12750. var _this = this;
  12751. return new Promise(function (res, rej) {
  12752. if (navigator.getVRDisplays) {
  12753. navigator.getVRDisplays().then(function (devices) {
  12754. _this._vrSupported = true;
  12755. // note that devices may actually be an empty array. This is fine;
  12756. // we expect this._vrDisplay to be undefined in this case.
  12757. _this._vrDisplay = devices[0];
  12758. res({
  12759. vrDisplay: _this._vrDisplay,
  12760. vrSupported: _this._vrSupported
  12761. });
  12762. });
  12763. }
  12764. else {
  12765. _this._vrDisplay = undefined;
  12766. _this._vrSupported = false;
  12767. res({
  12768. vrDisplay: _this._vrDisplay,
  12769. vrSupported: _this._vrSupported
  12770. });
  12771. }
  12772. });
  12773. };
  12774. /**
  12775. * Binds the frame buffer to the specified texture.
  12776. * @param texture The texture to render to or null for the default canvas
  12777. * @param faceIndex The face of the texture to render to in case of cube texture
  12778. * @param requiredWidth The width of the target to render to
  12779. * @param requiredHeight The height of the target to render to
  12780. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12781. * @param depthStencilTexture The depth stencil texture to use to render
  12782. * @param lodLevel defines le lod level to bind to the frame buffer
  12783. */
  12784. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12785. if (lodLevel === void 0) { lodLevel = 0; }
  12786. if (this._currentRenderTarget) {
  12787. this.unBindFramebuffer(this._currentRenderTarget);
  12788. }
  12789. this._currentRenderTarget = texture;
  12790. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12791. var gl = this._gl;
  12792. if (texture.isCube) {
  12793. if (faceIndex === undefined) {
  12794. faceIndex = 0;
  12795. }
  12796. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12797. if (depthStencilTexture) {
  12798. if (depthStencilTexture._generateStencilBuffer) {
  12799. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12800. }
  12801. else {
  12802. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12803. }
  12804. }
  12805. }
  12806. if (this._cachedViewport && !forceFullscreenViewport) {
  12807. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12808. }
  12809. else {
  12810. if (!requiredWidth) {
  12811. requiredWidth = texture.width;
  12812. if (lodLevel) {
  12813. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12814. }
  12815. }
  12816. if (!requiredHeight) {
  12817. requiredHeight = texture.height;
  12818. if (lodLevel) {
  12819. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12820. }
  12821. }
  12822. this._viewport(0, 0, requiredWidth, requiredHeight);
  12823. }
  12824. this.wipeCaches();
  12825. };
  12826. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12827. if (this._currentFramebuffer !== framebuffer) {
  12828. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12829. this._currentFramebuffer = framebuffer;
  12830. }
  12831. };
  12832. /**
  12833. * Unbind the current render target texture from the webGL context
  12834. * @param texture defines the render target texture to unbind
  12835. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12836. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12837. */
  12838. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12839. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12840. this._currentRenderTarget = null;
  12841. // If MSAA, we need to bitblt back to main texture
  12842. var gl = this._gl;
  12843. if (texture._MSAAFramebuffer) {
  12844. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12845. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12846. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12847. }
  12848. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12849. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12850. gl.generateMipmap(gl.TEXTURE_2D);
  12851. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12852. }
  12853. if (onBeforeUnbind) {
  12854. if (texture._MSAAFramebuffer) {
  12855. // Bind the correct framebuffer
  12856. this.bindUnboundFramebuffer(texture._framebuffer);
  12857. }
  12858. onBeforeUnbind();
  12859. }
  12860. this.bindUnboundFramebuffer(null);
  12861. };
  12862. /**
  12863. * Unbind a list of render target textures from the webGL context
  12864. * This is used only when drawBuffer extension or webGL2 are active
  12865. * @param textures defines the render target textures to unbind
  12866. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12867. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12868. */
  12869. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12870. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12871. this._currentRenderTarget = null;
  12872. // If MSAA, we need to bitblt back to main texture
  12873. var gl = this._gl;
  12874. if (textures[0]._MSAAFramebuffer) {
  12875. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12876. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12877. var attachments = textures[0]._attachments;
  12878. if (!attachments) {
  12879. attachments = new Array(textures.length);
  12880. textures[0]._attachments = attachments;
  12881. }
  12882. for (var i = 0; i < textures.length; i++) {
  12883. var texture = textures[i];
  12884. for (var j = 0; j < attachments.length; j++) {
  12885. attachments[j] = gl.NONE;
  12886. }
  12887. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12888. gl.readBuffer(attachments[i]);
  12889. gl.drawBuffers(attachments);
  12890. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12891. }
  12892. for (var i = 0; i < attachments.length; i++) {
  12893. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12894. }
  12895. gl.drawBuffers(attachments);
  12896. }
  12897. for (var i = 0; i < textures.length; i++) {
  12898. var texture = textures[i];
  12899. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12900. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12901. gl.generateMipmap(gl.TEXTURE_2D);
  12902. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12903. }
  12904. }
  12905. if (onBeforeUnbind) {
  12906. if (textures[0]._MSAAFramebuffer) {
  12907. // Bind the correct framebuffer
  12908. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12909. }
  12910. onBeforeUnbind();
  12911. }
  12912. this.bindUnboundFramebuffer(null);
  12913. };
  12914. /**
  12915. * Force the mipmap generation for the given render target texture
  12916. * @param texture defines the render target texture to use
  12917. */
  12918. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12919. if (texture.generateMipMaps) {
  12920. var gl = this._gl;
  12921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12922. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12923. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12924. }
  12925. };
  12926. /**
  12927. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12928. */
  12929. Engine.prototype.flushFramebuffer = function () {
  12930. this._gl.flush();
  12931. };
  12932. /**
  12933. * Unbind the current render target and bind the default framebuffer
  12934. */
  12935. Engine.prototype.restoreDefaultFramebuffer = function () {
  12936. if (this._currentRenderTarget) {
  12937. this.unBindFramebuffer(this._currentRenderTarget);
  12938. }
  12939. else {
  12940. this.bindUnboundFramebuffer(null);
  12941. }
  12942. if (this._cachedViewport) {
  12943. this.setViewport(this._cachedViewport);
  12944. }
  12945. this.wipeCaches();
  12946. };
  12947. // UBOs
  12948. /**
  12949. * Create an uniform buffer
  12950. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12951. * @param elements defines the content of the uniform buffer
  12952. * @returns the webGL uniform buffer
  12953. */
  12954. Engine.prototype.createUniformBuffer = function (elements) {
  12955. var ubo = this._gl.createBuffer();
  12956. if (!ubo) {
  12957. throw new Error("Unable to create uniform buffer");
  12958. }
  12959. this.bindUniformBuffer(ubo);
  12960. if (elements instanceof Float32Array) {
  12961. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12962. }
  12963. else {
  12964. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12965. }
  12966. this.bindUniformBuffer(null);
  12967. ubo.references = 1;
  12968. return ubo;
  12969. };
  12970. /**
  12971. * Create a dynamic uniform buffer
  12972. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12973. * @param elements defines the content of the uniform buffer
  12974. * @returns the webGL uniform buffer
  12975. */
  12976. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12977. var ubo = this._gl.createBuffer();
  12978. if (!ubo) {
  12979. throw new Error("Unable to create dynamic uniform buffer");
  12980. }
  12981. this.bindUniformBuffer(ubo);
  12982. if (elements instanceof Float32Array) {
  12983. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12984. }
  12985. else {
  12986. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12987. }
  12988. this.bindUniformBuffer(null);
  12989. ubo.references = 1;
  12990. return ubo;
  12991. };
  12992. /**
  12993. * Update an existing uniform buffer
  12994. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12995. * @param uniformBuffer defines the target uniform buffer
  12996. * @param elements defines the content to update
  12997. * @param offset defines the offset in the uniform buffer where update should start
  12998. * @param count defines the size of the data to update
  12999. */
  13000. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13001. this.bindUniformBuffer(uniformBuffer);
  13002. if (offset === undefined) {
  13003. offset = 0;
  13004. }
  13005. if (count === undefined) {
  13006. if (elements instanceof Float32Array) {
  13007. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13008. }
  13009. else {
  13010. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13011. }
  13012. }
  13013. else {
  13014. if (elements instanceof Float32Array) {
  13015. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13016. }
  13017. else {
  13018. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13019. }
  13020. }
  13021. this.bindUniformBuffer(null);
  13022. };
  13023. // VBOs
  13024. Engine.prototype._resetVertexBufferBinding = function () {
  13025. this.bindArrayBuffer(null);
  13026. this._cachedVertexBuffers = null;
  13027. };
  13028. /**
  13029. * Creates a vertex buffer
  13030. * @param data the data for the vertex buffer
  13031. * @returns the new WebGL static buffer
  13032. */
  13033. Engine.prototype.createVertexBuffer = function (data) {
  13034. var vbo = this._gl.createBuffer();
  13035. if (!vbo) {
  13036. throw new Error("Unable to create vertex buffer");
  13037. }
  13038. this.bindArrayBuffer(vbo);
  13039. if (data instanceof Array) {
  13040. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13041. }
  13042. else {
  13043. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13044. }
  13045. this._resetVertexBufferBinding();
  13046. vbo.references = 1;
  13047. return vbo;
  13048. };
  13049. /**
  13050. * Creates a dynamic vertex buffer
  13051. * @param data the data for the dynamic vertex buffer
  13052. * @returns the new WebGL dynamic buffer
  13053. */
  13054. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13055. var vbo = this._gl.createBuffer();
  13056. if (!vbo) {
  13057. throw new Error("Unable to create dynamic vertex buffer");
  13058. }
  13059. this.bindArrayBuffer(vbo);
  13060. if (data instanceof Array) {
  13061. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13062. }
  13063. else {
  13064. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13065. }
  13066. this._resetVertexBufferBinding();
  13067. vbo.references = 1;
  13068. return vbo;
  13069. };
  13070. /**
  13071. * Update a dynamic index buffer
  13072. * @param indexBuffer defines the target index buffer
  13073. * @param indices defines the data to update
  13074. * @param offset defines the offset in the target index buffer where update should start
  13075. */
  13076. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13077. if (offset === void 0) { offset = 0; }
  13078. // Force cache update
  13079. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13080. this.bindIndexBuffer(indexBuffer);
  13081. var arrayBuffer;
  13082. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13083. arrayBuffer = indices;
  13084. }
  13085. else {
  13086. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13087. }
  13088. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13089. this._resetIndexBufferBinding();
  13090. };
  13091. /**
  13092. * Updates a dynamic vertex buffer.
  13093. * @param vertexBuffer the vertex buffer to update
  13094. * @param data the data used to update the vertex buffer
  13095. * @param byteOffset the byte offset of the data
  13096. * @param byteLength the byte length of the data
  13097. */
  13098. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13099. this.bindArrayBuffer(vertexBuffer);
  13100. if (byteOffset === undefined) {
  13101. byteOffset = 0;
  13102. }
  13103. if (byteLength === undefined) {
  13104. if (data instanceof Array) {
  13105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13106. }
  13107. else {
  13108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13109. }
  13110. }
  13111. else {
  13112. if (data instanceof Array) {
  13113. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13114. }
  13115. else {
  13116. if (data instanceof ArrayBuffer) {
  13117. data = new Uint8Array(data, byteOffset, byteLength);
  13118. }
  13119. else {
  13120. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13121. }
  13122. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13123. }
  13124. }
  13125. this._resetVertexBufferBinding();
  13126. };
  13127. Engine.prototype._resetIndexBufferBinding = function () {
  13128. this.bindIndexBuffer(null);
  13129. this._cachedIndexBuffer = null;
  13130. };
  13131. /**
  13132. * Creates a new index buffer
  13133. * @param indices defines the content of the index buffer
  13134. * @param updatable defines if the index buffer must be updatable
  13135. * @returns a new webGL buffer
  13136. */
  13137. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13138. var vbo = this._gl.createBuffer();
  13139. if (!vbo) {
  13140. throw new Error("Unable to create index buffer");
  13141. }
  13142. this.bindIndexBuffer(vbo);
  13143. // Check for 32 bits indices
  13144. var arrayBuffer;
  13145. var need32Bits = false;
  13146. if (indices instanceof Uint16Array) {
  13147. arrayBuffer = indices;
  13148. }
  13149. else {
  13150. //check 32 bit support
  13151. if (this._caps.uintIndices) {
  13152. if (indices instanceof Uint32Array) {
  13153. arrayBuffer = indices;
  13154. need32Bits = true;
  13155. }
  13156. else {
  13157. //number[] or Int32Array, check if 32 bit is necessary
  13158. for (var index = 0; index < indices.length; index++) {
  13159. if (indices[index] > 65535) {
  13160. need32Bits = true;
  13161. break;
  13162. }
  13163. }
  13164. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13165. }
  13166. }
  13167. else {
  13168. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13169. arrayBuffer = new Uint16Array(indices);
  13170. }
  13171. }
  13172. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13173. this._resetIndexBufferBinding();
  13174. vbo.references = 1;
  13175. vbo.is32Bits = need32Bits;
  13176. return vbo;
  13177. };
  13178. /**
  13179. * Bind a webGL buffer to the webGL context
  13180. * @param buffer defines the buffer to bind
  13181. */
  13182. Engine.prototype.bindArrayBuffer = function (buffer) {
  13183. if (!this._vaoRecordInProgress) {
  13184. this._unbindVertexArrayObject();
  13185. }
  13186. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13187. };
  13188. /**
  13189. * Bind an uniform buffer to the current webGL context
  13190. * @param buffer defines the buffer to bind
  13191. */
  13192. Engine.prototype.bindUniformBuffer = function (buffer) {
  13193. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13194. };
  13195. /**
  13196. * Bind a buffer to the current webGL context at a given location
  13197. * @param buffer defines the buffer to bind
  13198. * @param location defines the index where to bind the buffer
  13199. */
  13200. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13201. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13202. };
  13203. /**
  13204. * Bind a specific block at a given index in a specific shader program
  13205. * @param shaderProgram defines the shader program
  13206. * @param blockName defines the block name
  13207. * @param index defines the index where to bind the block
  13208. */
  13209. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13210. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13211. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13212. };
  13213. ;
  13214. Engine.prototype.bindIndexBuffer = function (buffer) {
  13215. if (!this._vaoRecordInProgress) {
  13216. this._unbindVertexArrayObject();
  13217. }
  13218. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13219. };
  13220. Engine.prototype.bindBuffer = function (buffer, target) {
  13221. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13222. this._gl.bindBuffer(target, buffer);
  13223. this._currentBoundBuffer[target] = buffer;
  13224. }
  13225. };
  13226. /**
  13227. * update the bound buffer with the given data
  13228. * @param data defines the data to update
  13229. */
  13230. Engine.prototype.updateArrayBuffer = function (data) {
  13231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13232. };
  13233. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13234. var pointer = this._currentBufferPointers[indx];
  13235. var changed = false;
  13236. if (!pointer.active) {
  13237. changed = true;
  13238. pointer.active = true;
  13239. pointer.index = indx;
  13240. pointer.size = size;
  13241. pointer.type = type;
  13242. pointer.normalized = normalized;
  13243. pointer.stride = stride;
  13244. pointer.offset = offset;
  13245. pointer.buffer = buffer;
  13246. }
  13247. else {
  13248. if (pointer.buffer !== buffer) {
  13249. pointer.buffer = buffer;
  13250. changed = true;
  13251. }
  13252. if (pointer.size !== size) {
  13253. pointer.size = size;
  13254. changed = true;
  13255. }
  13256. if (pointer.type !== type) {
  13257. pointer.type = type;
  13258. changed = true;
  13259. }
  13260. if (pointer.normalized !== normalized) {
  13261. pointer.normalized = normalized;
  13262. changed = true;
  13263. }
  13264. if (pointer.stride !== stride) {
  13265. pointer.stride = stride;
  13266. changed = true;
  13267. }
  13268. if (pointer.offset !== offset) {
  13269. pointer.offset = offset;
  13270. changed = true;
  13271. }
  13272. }
  13273. if (changed || this._vaoRecordInProgress) {
  13274. this.bindArrayBuffer(buffer);
  13275. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13276. }
  13277. };
  13278. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13279. if (indexBuffer == null) {
  13280. return;
  13281. }
  13282. if (this._cachedIndexBuffer !== indexBuffer) {
  13283. this._cachedIndexBuffer = indexBuffer;
  13284. this.bindIndexBuffer(indexBuffer);
  13285. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13286. }
  13287. };
  13288. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13289. var attributes = effect.getAttributesNames();
  13290. if (!this._vaoRecordInProgress) {
  13291. this._unbindVertexArrayObject();
  13292. }
  13293. this.unbindAllAttributes();
  13294. for (var index = 0; index < attributes.length; index++) {
  13295. var order = effect.getAttributeLocation(index);
  13296. if (order >= 0) {
  13297. var vertexBuffer = vertexBuffers[attributes[index]];
  13298. if (!vertexBuffer) {
  13299. continue;
  13300. }
  13301. this._gl.enableVertexAttribArray(order);
  13302. if (!this._vaoRecordInProgress) {
  13303. this._vertexAttribArraysEnabled[order] = true;
  13304. }
  13305. var buffer = vertexBuffer.getBuffer();
  13306. if (buffer) {
  13307. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13308. if (vertexBuffer.getIsInstanced()) {
  13309. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13310. if (!this._vaoRecordInProgress) {
  13311. this._currentInstanceLocations.push(order);
  13312. this._currentInstanceBuffers.push(buffer);
  13313. }
  13314. }
  13315. }
  13316. }
  13317. }
  13318. };
  13319. /**
  13320. * Records a vertex array object
  13321. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13322. * @param vertexBuffers defines the list of vertex buffers to store
  13323. * @param indexBuffer defines the index buffer to store
  13324. * @param effect defines the effect to store
  13325. * @returns the new vertex array object
  13326. */
  13327. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13328. var vao = this._gl.createVertexArray();
  13329. this._vaoRecordInProgress = true;
  13330. this._gl.bindVertexArray(vao);
  13331. this._mustWipeVertexAttributes = true;
  13332. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13333. this.bindIndexBuffer(indexBuffer);
  13334. this._vaoRecordInProgress = false;
  13335. this._gl.bindVertexArray(null);
  13336. return vao;
  13337. };
  13338. /**
  13339. * Bind a specific vertex array object
  13340. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13341. * @param vertexArrayObject defines the vertex array object to bind
  13342. * @param indexBuffer defines the index buffer to bind
  13343. */
  13344. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13345. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13346. this._cachedVertexArrayObject = vertexArrayObject;
  13347. this._gl.bindVertexArray(vertexArrayObject);
  13348. this._cachedVertexBuffers = null;
  13349. this._cachedIndexBuffer = null;
  13350. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13351. this._mustWipeVertexAttributes = true;
  13352. }
  13353. };
  13354. /**
  13355. * Bind webGl buffers directly to the webGL context
  13356. * @param vertexBuffer defines the vertex buffer to bind
  13357. * @param indexBuffer defines the index buffer to bind
  13358. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13359. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13360. * @param effect defines the effect associated with the vertex buffer
  13361. */
  13362. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13363. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13364. this._cachedVertexBuffers = vertexBuffer;
  13365. this._cachedEffectForVertexBuffers = effect;
  13366. var attributesCount = effect.getAttributesCount();
  13367. this._unbindVertexArrayObject();
  13368. this.unbindAllAttributes();
  13369. var offset = 0;
  13370. for (var index = 0; index < attributesCount; index++) {
  13371. if (index < vertexDeclaration.length) {
  13372. var order = effect.getAttributeLocation(index);
  13373. if (order >= 0) {
  13374. this._gl.enableVertexAttribArray(order);
  13375. this._vertexAttribArraysEnabled[order] = true;
  13376. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13377. }
  13378. offset += vertexDeclaration[index] * 4;
  13379. }
  13380. }
  13381. }
  13382. this._bindIndexBufferWithCache(indexBuffer);
  13383. };
  13384. Engine.prototype._unbindVertexArrayObject = function () {
  13385. if (!this._cachedVertexArrayObject) {
  13386. return;
  13387. }
  13388. this._cachedVertexArrayObject = null;
  13389. this._gl.bindVertexArray(null);
  13390. };
  13391. /**
  13392. * Bind a list of vertex buffers to the webGL context
  13393. * @param vertexBuffers defines the list of vertex buffers to bind
  13394. * @param indexBuffer defines the index buffer to bind
  13395. * @param effect defines the effect associated with the vertex buffers
  13396. */
  13397. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13398. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13399. this._cachedVertexBuffers = vertexBuffers;
  13400. this._cachedEffectForVertexBuffers = effect;
  13401. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13402. }
  13403. this._bindIndexBufferWithCache(indexBuffer);
  13404. };
  13405. /**
  13406. * Unbind all instance attributes
  13407. */
  13408. Engine.prototype.unbindInstanceAttributes = function () {
  13409. var boundBuffer;
  13410. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13411. var instancesBuffer = this._currentInstanceBuffers[i];
  13412. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13413. boundBuffer = instancesBuffer;
  13414. this.bindArrayBuffer(instancesBuffer);
  13415. }
  13416. var offsetLocation = this._currentInstanceLocations[i];
  13417. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13418. }
  13419. this._currentInstanceBuffers.length = 0;
  13420. this._currentInstanceLocations.length = 0;
  13421. };
  13422. /**
  13423. * Release and free the memory of a vertex array object
  13424. * @param vao defines the vertex array object to delete
  13425. */
  13426. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13427. this._gl.deleteVertexArray(vao);
  13428. };
  13429. /** @hidden */
  13430. Engine.prototype._releaseBuffer = function (buffer) {
  13431. buffer.references--;
  13432. if (buffer.references === 0) {
  13433. this._gl.deleteBuffer(buffer);
  13434. return true;
  13435. }
  13436. return false;
  13437. };
  13438. /**
  13439. * Creates a webGL buffer to use with instanciation
  13440. * @param capacity defines the size of the buffer
  13441. * @returns the webGL buffer
  13442. */
  13443. Engine.prototype.createInstancesBuffer = function (capacity) {
  13444. var buffer = this._gl.createBuffer();
  13445. if (!buffer) {
  13446. throw new Error("Unable to create instance buffer");
  13447. }
  13448. buffer.capacity = capacity;
  13449. this.bindArrayBuffer(buffer);
  13450. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13451. return buffer;
  13452. };
  13453. /**
  13454. * Delete a webGL buffer used with instanciation
  13455. * @param buffer defines the webGL buffer to delete
  13456. */
  13457. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13458. this._gl.deleteBuffer(buffer);
  13459. };
  13460. /**
  13461. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13462. * @param instancesBuffer defines the webGL buffer to update and bind
  13463. * @param data defines the data to store in the buffer
  13464. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13465. */
  13466. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13467. this.bindArrayBuffer(instancesBuffer);
  13468. if (data) {
  13469. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13470. }
  13471. if (offsetLocations[0].index !== undefined) {
  13472. var stride = 0;
  13473. for (var i = 0; i < offsetLocations.length; i++) {
  13474. var ai = offsetLocations[i];
  13475. stride += ai.attributeSize * 4;
  13476. }
  13477. for (var i = 0; i < offsetLocations.length; i++) {
  13478. var ai = offsetLocations[i];
  13479. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13480. this._gl.enableVertexAttribArray(ai.index);
  13481. this._vertexAttribArraysEnabled[ai.index] = true;
  13482. }
  13483. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13484. this._gl.vertexAttribDivisor(ai.index, 1);
  13485. this._currentInstanceLocations.push(ai.index);
  13486. this._currentInstanceBuffers.push(instancesBuffer);
  13487. }
  13488. }
  13489. else {
  13490. for (var index = 0; index < 4; index++) {
  13491. var offsetLocation = offsetLocations[index];
  13492. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13493. this._gl.enableVertexAttribArray(offsetLocation);
  13494. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13495. }
  13496. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13497. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13498. this._currentInstanceLocations.push(offsetLocation);
  13499. this._currentInstanceBuffers.push(instancesBuffer);
  13500. }
  13501. }
  13502. };
  13503. /**
  13504. * Apply all cached states (depth, culling, stencil and alpha)
  13505. */
  13506. Engine.prototype.applyStates = function () {
  13507. this._depthCullingState.apply(this._gl);
  13508. this._stencilState.apply(this._gl);
  13509. this._alphaState.apply(this._gl);
  13510. };
  13511. /**
  13512. * Send a draw order
  13513. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13514. * @param indexStart defines the starting index
  13515. * @param indexCount defines the number of index to draw
  13516. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13517. */
  13518. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13519. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13520. };
  13521. /**
  13522. * Draw a list of points
  13523. * @param verticesStart defines the index of first vertex to draw
  13524. * @param verticesCount defines the count of vertices to draw
  13525. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13526. */
  13527. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13528. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13529. };
  13530. /**
  13531. * Draw a list of unindexed primitives
  13532. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13533. * @param verticesStart defines the index of first vertex to draw
  13534. * @param verticesCount defines the count of vertices to draw
  13535. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13536. */
  13537. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13538. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13539. };
  13540. /**
  13541. * Draw a list of indexed primitives
  13542. * @param fillMode defines the primitive to use
  13543. * @param indexStart defines the starting index
  13544. * @param indexCount defines the number of index to draw
  13545. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13546. */
  13547. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13548. // Apply states
  13549. this.applyStates();
  13550. this._drawCalls.addCount(1, false);
  13551. // Render
  13552. var drawMode = this._drawMode(fillMode);
  13553. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13554. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13555. if (instancesCount) {
  13556. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13557. }
  13558. else {
  13559. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13560. }
  13561. };
  13562. /**
  13563. * Draw a list of unindexed primitives
  13564. * @param fillMode defines the primitive to use
  13565. * @param verticesStart defines the index of first vertex to draw
  13566. * @param verticesCount defines the count of vertices to draw
  13567. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13568. */
  13569. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13570. // Apply states
  13571. this.applyStates();
  13572. this._drawCalls.addCount(1, false);
  13573. var drawMode = this._drawMode(fillMode);
  13574. if (instancesCount) {
  13575. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13576. }
  13577. else {
  13578. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13579. }
  13580. };
  13581. Engine.prototype._drawMode = function (fillMode) {
  13582. switch (fillMode) {
  13583. // Triangle views
  13584. case BABYLON.Material.TriangleFillMode:
  13585. return this._gl.TRIANGLES;
  13586. case BABYLON.Material.PointFillMode:
  13587. return this._gl.POINTS;
  13588. case BABYLON.Material.WireFrameFillMode:
  13589. return this._gl.LINES;
  13590. // Draw modes
  13591. case BABYLON.Material.PointListDrawMode:
  13592. return this._gl.POINTS;
  13593. case BABYLON.Material.LineListDrawMode:
  13594. return this._gl.LINES;
  13595. case BABYLON.Material.LineLoopDrawMode:
  13596. return this._gl.LINE_LOOP;
  13597. case BABYLON.Material.LineStripDrawMode:
  13598. return this._gl.LINE_STRIP;
  13599. case BABYLON.Material.TriangleStripDrawMode:
  13600. return this._gl.TRIANGLE_STRIP;
  13601. case BABYLON.Material.TriangleFanDrawMode:
  13602. return this._gl.TRIANGLE_FAN;
  13603. default:
  13604. return this._gl.TRIANGLES;
  13605. }
  13606. };
  13607. // Shaders
  13608. /** @hidden */
  13609. Engine.prototype._releaseEffect = function (effect) {
  13610. if (this._compiledEffects[effect._key]) {
  13611. delete this._compiledEffects[effect._key];
  13612. this._deleteProgram(effect.getProgram());
  13613. }
  13614. };
  13615. /** @hidden */
  13616. Engine.prototype._deleteProgram = function (program) {
  13617. if (program) {
  13618. program.__SPECTOR_rebuildProgram = null;
  13619. if (program.transformFeedback) {
  13620. this.deleteTransformFeedback(program.transformFeedback);
  13621. program.transformFeedback = null;
  13622. }
  13623. this._gl.deleteProgram(program);
  13624. }
  13625. };
  13626. /**
  13627. * Create a new effect (used to store vertex/fragment shaders)
  13628. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13629. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13630. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13631. * @param samplers defines an array of string used to represent textures
  13632. * @param defines defines the string containing the defines to use to compile the shaders
  13633. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13634. * @param onCompiled defines a function to call when the effect creation is successful
  13635. * @param onError defines a function to call when the effect creation has failed
  13636. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13637. * @returns the new Effect
  13638. */
  13639. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13640. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13641. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13642. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13643. if (this._compiledEffects[name]) {
  13644. var compiledEffect = this._compiledEffects[name];
  13645. if (onCompiled && compiledEffect.isReady()) {
  13646. onCompiled(compiledEffect);
  13647. }
  13648. return compiledEffect;
  13649. }
  13650. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13651. effect._key = name;
  13652. this._compiledEffects[name] = effect;
  13653. return effect;
  13654. };
  13655. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13656. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13657. };
  13658. ;
  13659. Engine.prototype._compileRawShader = function (source, type) {
  13660. var gl = this._gl;
  13661. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13662. gl.shaderSource(shader, source);
  13663. gl.compileShader(shader);
  13664. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13665. var log = gl.getShaderInfoLog(shader);
  13666. if (log) {
  13667. throw new Error(log);
  13668. }
  13669. }
  13670. if (!shader) {
  13671. throw new Error("Something went wrong while compile the shader.");
  13672. }
  13673. return shader;
  13674. };
  13675. ;
  13676. /**
  13677. * Directly creates a webGL program
  13678. * @param vertexCode defines the vertex shader code to use
  13679. * @param fragmentCode defines the fragment shader code to use
  13680. * @param context defines the webGL context to use (if not set, the current one will be used)
  13681. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13682. * @returns the new webGL program
  13683. */
  13684. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13685. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13686. context = context || this._gl;
  13687. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13688. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13689. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13690. };
  13691. /**
  13692. * Creates a webGL program
  13693. * @param vertexCode defines the vertex shader code to use
  13694. * @param fragmentCode defines the fragment shader code to use
  13695. * @param defines defines the string containing the defines to use to compile the shaders
  13696. * @param context defines the webGL context to use (if not set, the current one will be used)
  13697. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13698. * @returns the new webGL program
  13699. */
  13700. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13701. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13702. context = context || this._gl;
  13703. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13704. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13705. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13706. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13707. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13708. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13709. return program;
  13710. };
  13711. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13712. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13713. var shaderProgram = context.createProgram();
  13714. if (!shaderProgram) {
  13715. throw new Error("Unable to create program");
  13716. }
  13717. context.attachShader(shaderProgram, vertexShader);
  13718. context.attachShader(shaderProgram, fragmentShader);
  13719. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13720. var transformFeedback = this.createTransformFeedback();
  13721. this.bindTransformFeedback(transformFeedback);
  13722. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13723. shaderProgram.transformFeedback = transformFeedback;
  13724. }
  13725. context.linkProgram(shaderProgram);
  13726. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13727. this.bindTransformFeedback(null);
  13728. }
  13729. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13730. if (!linked) {
  13731. var error = context.getProgramInfoLog(shaderProgram);
  13732. if (error) {
  13733. throw new Error(error);
  13734. }
  13735. }
  13736. if (this.validateShaderPrograms) {
  13737. context.validateProgram(shaderProgram);
  13738. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13739. if (!validated) {
  13740. var error = context.getProgramInfoLog(shaderProgram);
  13741. if (error) {
  13742. throw new Error(error);
  13743. }
  13744. }
  13745. }
  13746. context.deleteShader(vertexShader);
  13747. context.deleteShader(fragmentShader);
  13748. return shaderProgram;
  13749. };
  13750. /**
  13751. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13752. * @param shaderProgram defines the webGL program to use
  13753. * @param uniformsNames defines the list of uniform names
  13754. * @returns an array of webGL uniform locations
  13755. */
  13756. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13757. var results = new Array();
  13758. for (var index = 0; index < uniformsNames.length; index++) {
  13759. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13760. }
  13761. return results;
  13762. };
  13763. /**
  13764. * Gets the lsit of active attributes for a given webGL program
  13765. * @param shaderProgram defines the webGL program to use
  13766. * @param attributesNames defines the list of attribute names to get
  13767. * @returns an array of indices indicating the offset of each attribute
  13768. */
  13769. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13770. var results = [];
  13771. for (var index = 0; index < attributesNames.length; index++) {
  13772. try {
  13773. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13774. }
  13775. catch (e) {
  13776. results.push(-1);
  13777. }
  13778. }
  13779. return results;
  13780. };
  13781. /**
  13782. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13783. * @param effect defines the effect to activate
  13784. */
  13785. Engine.prototype.enableEffect = function (effect) {
  13786. if (!effect || effect === this._currentEffect) {
  13787. return;
  13788. }
  13789. // Use program
  13790. this.bindSamplers(effect);
  13791. this._currentEffect = effect;
  13792. if (effect.onBind) {
  13793. effect.onBind(effect);
  13794. }
  13795. if (effect._onBindObservable) {
  13796. effect._onBindObservable.notifyObservers(effect);
  13797. }
  13798. };
  13799. /**
  13800. * Set the value of an uniform to an array of int32
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param array defines the array of int32 to store
  13803. */
  13804. Engine.prototype.setIntArray = function (uniform, array) {
  13805. if (!uniform)
  13806. return;
  13807. this._gl.uniform1iv(uniform, array);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to an array of int32 (stored as vec2)
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param array defines the array of int32 to store
  13813. */
  13814. Engine.prototype.setIntArray2 = function (uniform, array) {
  13815. if (!uniform || array.length % 2 !== 0)
  13816. return;
  13817. this._gl.uniform2iv(uniform, array);
  13818. };
  13819. /**
  13820. * Set the value of an uniform to an array of int32 (stored as vec3)
  13821. * @param uniform defines the webGL uniform location where to store the value
  13822. * @param array defines the array of int32 to store
  13823. */
  13824. Engine.prototype.setIntArray3 = function (uniform, array) {
  13825. if (!uniform || array.length % 3 !== 0)
  13826. return;
  13827. this._gl.uniform3iv(uniform, array);
  13828. };
  13829. /**
  13830. * Set the value of an uniform to an array of int32 (stored as vec4)
  13831. * @param uniform defines the webGL uniform location where to store the value
  13832. * @param array defines the array of int32 to store
  13833. */
  13834. Engine.prototype.setIntArray4 = function (uniform, array) {
  13835. if (!uniform || array.length % 4 !== 0)
  13836. return;
  13837. this._gl.uniform4iv(uniform, array);
  13838. };
  13839. /**
  13840. * Set the value of an uniform to an array of float32
  13841. * @param uniform defines the webGL uniform location where to store the value
  13842. * @param array defines the array of float32 to store
  13843. */
  13844. Engine.prototype.setFloatArray = function (uniform, array) {
  13845. if (!uniform)
  13846. return;
  13847. this._gl.uniform1fv(uniform, array);
  13848. };
  13849. /**
  13850. * Set the value of an uniform to an array of float32 (stored as vec2)
  13851. * @param uniform defines the webGL uniform location where to store the value
  13852. * @param array defines the array of float32 to store
  13853. */
  13854. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13855. if (!uniform || array.length % 2 !== 0)
  13856. return;
  13857. this._gl.uniform2fv(uniform, array);
  13858. };
  13859. /**
  13860. * Set the value of an uniform to an array of float32 (stored as vec3)
  13861. * @param uniform defines the webGL uniform location where to store the value
  13862. * @param array defines the array of float32 to store
  13863. */
  13864. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13865. if (!uniform || array.length % 3 !== 0)
  13866. return;
  13867. this._gl.uniform3fv(uniform, array);
  13868. };
  13869. /**
  13870. * Set the value of an uniform to an array of float32 (stored as vec4)
  13871. * @param uniform defines the webGL uniform location where to store the value
  13872. * @param array defines the array of float32 to store
  13873. */
  13874. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13875. if (!uniform || array.length % 4 !== 0)
  13876. return;
  13877. this._gl.uniform4fv(uniform, array);
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of number
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of number to store
  13883. */
  13884. Engine.prototype.setArray = function (uniform, array) {
  13885. if (!uniform)
  13886. return;
  13887. this._gl.uniform1fv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of number (stored as vec2)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of number to store
  13893. */
  13894. Engine.prototype.setArray2 = function (uniform, array) {
  13895. if (!uniform || array.length % 2 !== 0)
  13896. return;
  13897. this._gl.uniform2fv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of number (stored as vec3)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param array defines the array of number to store
  13903. */
  13904. Engine.prototype.setArray3 = function (uniform, array) {
  13905. if (!uniform || array.length % 3 !== 0)
  13906. return;
  13907. this._gl.uniform3fv(uniform, array);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to an array of number (stored as vec4)
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param array defines the array of number to store
  13913. */
  13914. Engine.prototype.setArray4 = function (uniform, array) {
  13915. if (!uniform || array.length % 4 !== 0)
  13916. return;
  13917. this._gl.uniform4fv(uniform, array);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to an array of float32 (stored as matrices)
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param matrices defines the array of float32 to store
  13923. */
  13924. Engine.prototype.setMatrices = function (uniform, matrices) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a matrix
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param matrix defines the matrix to store
  13933. */
  13934. Engine.prototype.setMatrix = function (uniform, matrix) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13938. };
  13939. /**
  13940. * Set the value of an uniform to a matrix (3x3)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13943. */
  13944. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13945. if (!uniform)
  13946. return;
  13947. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to a matrix (2x2)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13953. */
  13954. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13955. if (!uniform)
  13956. return;
  13957. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to a number (int)
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param value defines the int number to store
  13963. */
  13964. Engine.prototype.setInt = function (uniform, value) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform1i(uniform, value);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to a number (float)
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param value defines the float number to store
  13973. */
  13974. Engine.prototype.setFloat = function (uniform, value) {
  13975. if (!uniform)
  13976. return;
  13977. this._gl.uniform1f(uniform, value);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to a vec2
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param x defines the 1st component of the value
  13983. * @param y defines the 2nd component of the value
  13984. */
  13985. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13986. if (!uniform)
  13987. return;
  13988. this._gl.uniform2f(uniform, x, y);
  13989. };
  13990. /**
  13991. * Set the value of an uniform to a vec3
  13992. * @param uniform defines the webGL uniform location where to store the value
  13993. * @param x defines the 1st component of the value
  13994. * @param y defines the 2nd component of the value
  13995. * @param z defines the 3rd component of the value
  13996. */
  13997. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13998. if (!uniform)
  13999. return;
  14000. this._gl.uniform3f(uniform, x, y, z);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to a boolean
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param bool defines the boolean to store
  14006. */
  14007. Engine.prototype.setBool = function (uniform, bool) {
  14008. if (!uniform)
  14009. return;
  14010. this._gl.uniform1i(uniform, bool);
  14011. };
  14012. /**
  14013. * Set the value of an uniform to a vec4
  14014. * @param uniform defines the webGL uniform location where to store the value
  14015. * @param x defines the 1st component of the value
  14016. * @param y defines the 2nd component of the value
  14017. * @param z defines the 3rd component of the value
  14018. * @param w defines the 4th component of the value
  14019. */
  14020. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14021. if (!uniform)
  14022. return;
  14023. this._gl.uniform4f(uniform, x, y, z, w);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to a Color3
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param color3 defines the color to store
  14029. */
  14030. Engine.prototype.setColor3 = function (uniform, color3) {
  14031. if (!uniform)
  14032. return;
  14033. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to a Color3 and an alpha value
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param color3 defines the color to store
  14039. * @param alpha defines the alpha component to store
  14040. */
  14041. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14042. if (!uniform)
  14043. return;
  14044. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14045. };
  14046. /**
  14047. * Sets a Color4 on a uniform variable
  14048. * @param uniform defines the uniform location
  14049. * @param color4 defines the value to be set
  14050. */
  14051. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14052. if (!uniform)
  14053. return;
  14054. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14055. };
  14056. // States
  14057. /**
  14058. * Set various states to the webGL context
  14059. * @param culling defines backface culling state
  14060. * @param zOffset defines the value to apply to zOffset (0 by default)
  14061. * @param force defines if states must be applied even if cache is up to date
  14062. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14063. */
  14064. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14065. if (zOffset === void 0) { zOffset = 0; }
  14066. if (reverseSide === void 0) { reverseSide = false; }
  14067. // Culling
  14068. if (this._depthCullingState.cull !== culling || force) {
  14069. this._depthCullingState.cull = culling;
  14070. }
  14071. // Cull face
  14072. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14073. if (this._depthCullingState.cullFace !== cullFace || force) {
  14074. this._depthCullingState.cullFace = cullFace;
  14075. }
  14076. // Z offset
  14077. this.setZOffset(zOffset);
  14078. // Front face
  14079. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14080. if (this._depthCullingState.frontFace !== frontFace || force) {
  14081. this._depthCullingState.frontFace = frontFace;
  14082. }
  14083. };
  14084. /**
  14085. * Set the z offset to apply to current rendering
  14086. * @param value defines the offset to apply
  14087. */
  14088. Engine.prototype.setZOffset = function (value) {
  14089. this._depthCullingState.zOffset = value;
  14090. };
  14091. /**
  14092. * Gets the current value of the zOffset
  14093. * @returns the current zOffset state
  14094. */
  14095. Engine.prototype.getZOffset = function () {
  14096. return this._depthCullingState.zOffset;
  14097. };
  14098. /**
  14099. * Enable or disable depth buffering
  14100. * @param enable defines the state to set
  14101. */
  14102. Engine.prototype.setDepthBuffer = function (enable) {
  14103. this._depthCullingState.depthTest = enable;
  14104. };
  14105. /**
  14106. * Gets a boolean indicating if depth writing is enabled
  14107. * @returns the current depth writing state
  14108. */
  14109. Engine.prototype.getDepthWrite = function () {
  14110. return this._depthCullingState.depthMask;
  14111. };
  14112. /**
  14113. * Enable or disable depth writing
  14114. * @param enable defines the state to set
  14115. */
  14116. Engine.prototype.setDepthWrite = function (enable) {
  14117. this._depthCullingState.depthMask = enable;
  14118. };
  14119. /**
  14120. * Enable or disable color writing
  14121. * @param enable defines the state to set
  14122. */
  14123. Engine.prototype.setColorWrite = function (enable) {
  14124. this._gl.colorMask(enable, enable, enable, enable);
  14125. this._colorWrite = enable;
  14126. };
  14127. /**
  14128. * Gets a boolean indicating if color writing is enabled
  14129. * @returns the current color writing state
  14130. */
  14131. Engine.prototype.getColorWrite = function () {
  14132. return this._colorWrite;
  14133. };
  14134. /**
  14135. * Sets alpha constants used by some alpha blending modes
  14136. * @param r defines the red component
  14137. * @param g defines the green component
  14138. * @param b defines the blue component
  14139. * @param a defines the alpha component
  14140. */
  14141. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14142. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14143. };
  14144. /**
  14145. * Sets the current alpha mode
  14146. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14147. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14148. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14149. */
  14150. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14151. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14152. if (this._alphaMode === mode) {
  14153. return;
  14154. }
  14155. switch (mode) {
  14156. case Engine.ALPHA_DISABLE:
  14157. this._alphaState.alphaBlend = false;
  14158. break;
  14159. case Engine.ALPHA_PREMULTIPLIED:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_COMBINE:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_ONEONE:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. case Engine.ALPHA_ADD:
  14176. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14177. this._alphaState.alphaBlend = true;
  14178. break;
  14179. case Engine.ALPHA_SUBTRACT:
  14180. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14181. this._alphaState.alphaBlend = true;
  14182. break;
  14183. case Engine.ALPHA_MULTIPLY:
  14184. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14185. this._alphaState.alphaBlend = true;
  14186. break;
  14187. case Engine.ALPHA_MAXIMIZED:
  14188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14189. this._alphaState.alphaBlend = true;
  14190. break;
  14191. case Engine.ALPHA_INTERPOLATE:
  14192. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14193. this._alphaState.alphaBlend = true;
  14194. break;
  14195. case Engine.ALPHA_SCREENMODE:
  14196. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14197. this._alphaState.alphaBlend = true;
  14198. break;
  14199. }
  14200. if (!noDepthWriteChange) {
  14201. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14202. }
  14203. this._alphaMode = mode;
  14204. };
  14205. /**
  14206. * Gets the current alpha mode
  14207. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14208. * @returns the current alpha mode
  14209. */
  14210. Engine.prototype.getAlphaMode = function () {
  14211. return this._alphaMode;
  14212. };
  14213. // Textures
  14214. /**
  14215. * Clears the list of texture accessible through engine.
  14216. * This can help preventing texture load conflict due to name collision.
  14217. */
  14218. Engine.prototype.clearInternalTexturesCache = function () {
  14219. this._internalTexturesCache = [];
  14220. };
  14221. /**
  14222. * Force the entire cache to be cleared
  14223. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14224. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14225. */
  14226. Engine.prototype.wipeCaches = function (bruteForce) {
  14227. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14228. return;
  14229. }
  14230. this._currentEffect = null;
  14231. this._unpackFlipYCached = null;
  14232. this._viewportCached.x = 0;
  14233. this._viewportCached.y = 0;
  14234. this._viewportCached.z = 0;
  14235. this._viewportCached.w = 0;
  14236. if (bruteForce) {
  14237. this.resetTextureCache();
  14238. this._currentProgram = null;
  14239. this._stencilState.reset();
  14240. this._depthCullingState.reset();
  14241. this.setDepthFunctionToLessOrEqual();
  14242. this._alphaState.reset();
  14243. }
  14244. this._resetVertexBufferBinding();
  14245. this._cachedIndexBuffer = null;
  14246. this._cachedEffectForVertexBuffers = null;
  14247. this._unbindVertexArrayObject();
  14248. this.bindIndexBuffer(null);
  14249. };
  14250. /**
  14251. * Set the compressed texture format to use, based on the formats you have, and the formats
  14252. * supported by the hardware / browser.
  14253. *
  14254. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14255. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14256. * to API arguments needed to compressed textures. This puts the burden on the container
  14257. * generator to house the arcane code for determining these for current & future formats.
  14258. *
  14259. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14260. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14261. *
  14262. * Note: The result of this call is not taken into account when a texture is base64.
  14263. *
  14264. * @param formatsAvailable defines the list of those format families you have created
  14265. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14266. *
  14267. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14268. * @returns The extension selected.
  14269. */
  14270. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14271. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14272. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14273. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14274. return this._textureFormatInUse = this._texturesSupported[i];
  14275. }
  14276. }
  14277. }
  14278. // actively set format to nothing, to allow this to be called more than once
  14279. // and possibly fail the 2nd time
  14280. this._textureFormatInUse = null;
  14281. return null;
  14282. };
  14283. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14284. var gl = this._gl;
  14285. var magFilter = gl.NEAREST;
  14286. var minFilter = gl.NEAREST;
  14287. switch (samplingMode) {
  14288. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14289. magFilter = gl.LINEAR;
  14290. if (generateMipMaps) {
  14291. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14292. }
  14293. else {
  14294. minFilter = gl.LINEAR;
  14295. }
  14296. break;
  14297. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14298. magFilter = gl.LINEAR;
  14299. if (generateMipMaps) {
  14300. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14301. }
  14302. else {
  14303. minFilter = gl.LINEAR;
  14304. }
  14305. break;
  14306. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14307. magFilter = gl.NEAREST;
  14308. if (generateMipMaps) {
  14309. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14310. }
  14311. else {
  14312. minFilter = gl.NEAREST;
  14313. }
  14314. break;
  14315. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14316. magFilter = gl.NEAREST;
  14317. if (generateMipMaps) {
  14318. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14319. }
  14320. else {
  14321. minFilter = gl.NEAREST;
  14322. }
  14323. break;
  14324. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14325. magFilter = gl.NEAREST;
  14326. if (generateMipMaps) {
  14327. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14328. }
  14329. else {
  14330. minFilter = gl.LINEAR;
  14331. }
  14332. break;
  14333. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14334. magFilter = gl.NEAREST;
  14335. if (generateMipMaps) {
  14336. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14337. }
  14338. else {
  14339. minFilter = gl.LINEAR;
  14340. }
  14341. break;
  14342. case Engine.TEXTURE_NEAREST_LINEAR:
  14343. magFilter = gl.NEAREST;
  14344. minFilter = gl.LINEAR;
  14345. break;
  14346. case Engine.TEXTURE_NEAREST_NEAREST:
  14347. magFilter = gl.NEAREST;
  14348. minFilter = gl.NEAREST;
  14349. break;
  14350. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14351. magFilter = gl.LINEAR;
  14352. if (generateMipMaps) {
  14353. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14354. }
  14355. else {
  14356. minFilter = gl.NEAREST;
  14357. }
  14358. break;
  14359. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14360. magFilter = gl.LINEAR;
  14361. if (generateMipMaps) {
  14362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14363. }
  14364. else {
  14365. minFilter = gl.NEAREST;
  14366. }
  14367. break;
  14368. case Engine.TEXTURE_LINEAR_LINEAR:
  14369. magFilter = gl.LINEAR;
  14370. minFilter = gl.LINEAR;
  14371. break;
  14372. case Engine.TEXTURE_LINEAR_NEAREST:
  14373. magFilter = gl.LINEAR;
  14374. minFilter = gl.NEAREST;
  14375. break;
  14376. }
  14377. return {
  14378. min: minFilter,
  14379. mag: magFilter
  14380. };
  14381. };
  14382. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14383. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14384. var img;
  14385. var onload = function () {
  14386. loadedImages[index] = img;
  14387. loadedImages._internalCount++;
  14388. if (scene) {
  14389. scene._removePendingData(img);
  14390. }
  14391. if (loadedImages._internalCount === 6) {
  14392. onfinish(loadedImages);
  14393. }
  14394. };
  14395. var onerror = function (message, exception) {
  14396. if (scene) {
  14397. scene._removePendingData(img);
  14398. }
  14399. if (onErrorCallBack) {
  14400. onErrorCallBack(message, exception);
  14401. }
  14402. };
  14403. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14404. if (scene) {
  14405. scene._addPendingData(img);
  14406. }
  14407. };
  14408. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14409. if (onError === void 0) { onError = null; }
  14410. var loadedImages = [];
  14411. loadedImages._internalCount = 0;
  14412. for (var index = 0; index < 6; index++) {
  14413. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14414. }
  14415. };
  14416. ;
  14417. /** @hidden */
  14418. Engine.prototype._createTexture = function () {
  14419. var texture = this._gl.createTexture();
  14420. if (!texture) {
  14421. throw new Error("Unable to create texture");
  14422. }
  14423. return texture;
  14424. };
  14425. /**
  14426. * Usually called from BABYLON.Texture.ts.
  14427. * Passed information to create a WebGLTexture
  14428. * @param urlArg defines a value which contains one of the following:
  14429. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14430. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14431. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14432. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14433. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14434. * @param scene needed for loading to the correct scene
  14435. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14436. * @param onLoad optional callback to be called upon successful completion
  14437. * @param onError optional callback to be called upon failure
  14438. * @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
  14439. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14440. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14441. * @param forcedExtension defines the extension to use to pick the right loader
  14442. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14443. */
  14444. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14445. var _this = this;
  14446. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14447. if (onLoad === void 0) { onLoad = null; }
  14448. if (onError === void 0) { onError = null; }
  14449. if (buffer === void 0) { buffer = null; }
  14450. if (fallback === void 0) { fallback = null; }
  14451. if (format === void 0) { format = null; }
  14452. if (forcedExtension === void 0) { forcedExtension = null; }
  14453. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14454. var fromData = url.substr(0, 5) === "data:";
  14455. var fromBlob = url.substr(0, 5) === "blob:";
  14456. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14457. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14458. // establish the file extension, if possible
  14459. var lastDot = url.lastIndexOf('.');
  14460. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14461. var loader = null;
  14462. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14463. var availableLoader = _a[_i];
  14464. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14465. loader = availableLoader;
  14466. break;
  14467. }
  14468. }
  14469. if (loader) {
  14470. url = loader.transformUrl(url, this._textureFormatInUse);
  14471. }
  14472. if (scene) {
  14473. scene._addPendingData(texture);
  14474. }
  14475. texture.url = url;
  14476. texture.generateMipMaps = !noMipmap;
  14477. texture.samplingMode = samplingMode;
  14478. texture.invertY = invertY;
  14479. if (!this._doNotHandleContextLost) {
  14480. // Keep a link to the buffer only if we plan to handle context lost
  14481. texture._buffer = buffer;
  14482. }
  14483. var onLoadObserver = null;
  14484. if (onLoad && !fallback) {
  14485. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14486. }
  14487. if (!fallback)
  14488. this._internalTexturesCache.push(texture);
  14489. var onInternalError = function (message, exception) {
  14490. if (scene) {
  14491. scene._removePendingData(texture);
  14492. }
  14493. var customFallback = false;
  14494. if (loader) {
  14495. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14496. if (fallbackUrl) {
  14497. // Add Back
  14498. customFallback = true;
  14499. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14500. }
  14501. }
  14502. if (!customFallback) {
  14503. if (onLoadObserver) {
  14504. texture.onLoadedObservable.remove(onLoadObserver);
  14505. }
  14506. if (BABYLON.Tools.UseFallbackTexture) {
  14507. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14508. }
  14509. }
  14510. if (onError) {
  14511. onError(message || "Unknown error", exception);
  14512. }
  14513. };
  14514. // processing for non-image formats
  14515. if (loader) {
  14516. var callback = function (data) {
  14517. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14518. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14519. done();
  14520. return false;
  14521. }, samplingMode);
  14522. });
  14523. };
  14524. if (!buffer) {
  14525. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14526. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14527. });
  14528. }
  14529. else {
  14530. callback(buffer);
  14531. }
  14532. }
  14533. else {
  14534. var onload = function (img) {
  14535. if (fromBlob && !_this._doNotHandleContextLost) {
  14536. // We need to store the image if we need to rebuild the texture
  14537. // in case of a webgl context lost
  14538. texture._buffer = img;
  14539. }
  14540. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14541. var gl = _this._gl;
  14542. var isPot = (img.width === potWidth && img.height === potHeight);
  14543. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14544. if (isPot) {
  14545. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14546. return false;
  14547. }
  14548. var maxTextureSize = _this._caps.maxTextureSize;
  14549. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14550. _this._prepareWorkingCanvas();
  14551. if (!_this._workingCanvas || !_this._workingContext) {
  14552. return false;
  14553. }
  14554. _this._workingCanvas.width = potWidth;
  14555. _this._workingCanvas.height = potHeight;
  14556. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14557. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14558. texture.width = potWidth;
  14559. texture.height = potHeight;
  14560. return false;
  14561. }
  14562. else {
  14563. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14564. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14565. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14566. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14571. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14572. _this._releaseTexture(source_1);
  14573. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14574. continuationCallback();
  14575. });
  14576. }
  14577. return true;
  14578. }, samplingMode);
  14579. };
  14580. if (!fromData || isBase64) {
  14581. if (buffer instanceof HTMLImageElement) {
  14582. onload(buffer);
  14583. }
  14584. else {
  14585. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14586. }
  14587. }
  14588. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14589. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14590. }
  14591. else {
  14592. onload(buffer);
  14593. }
  14594. }
  14595. return texture;
  14596. };
  14597. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14598. var _this = this;
  14599. var rtt = this.createRenderTargetTexture({
  14600. width: destination.width,
  14601. height: destination.height,
  14602. }, {
  14603. generateMipMaps: false,
  14604. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14605. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14606. generateDepthBuffer: false,
  14607. generateStencilBuffer: false
  14608. });
  14609. if (!this._rescalePostProcess) {
  14610. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14611. }
  14612. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14613. _this._rescalePostProcess.onApply = function (effect) {
  14614. effect._bindTexture("textureSampler", source);
  14615. };
  14616. var hostingScene = scene;
  14617. if (!hostingScene) {
  14618. hostingScene = _this.scenes[_this.scenes.length - 1];
  14619. }
  14620. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14621. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14622. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14623. _this.unBindFramebuffer(rtt);
  14624. _this._releaseTexture(rtt);
  14625. if (onComplete) {
  14626. onComplete();
  14627. }
  14628. });
  14629. };
  14630. /**
  14631. * Update a raw texture
  14632. * @param texture defines the texture to update
  14633. * @param data defines the data to store in the texture
  14634. * @param format defines the format of the data
  14635. * @param invertY defines if data must be stored with Y axis inverted
  14636. * @param compression defines the compression used (null by default)
  14637. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14638. */
  14639. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14640. if (compression === void 0) { compression = null; }
  14641. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14642. if (!texture) {
  14643. return;
  14644. }
  14645. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14646. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14647. // babylon's internalFormat but gl's texImage2D format
  14648. var internalFormat = this._getInternalFormat(format);
  14649. var textureType = this._getWebGLTextureType(type);
  14650. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14651. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14652. if (!this._doNotHandleContextLost) {
  14653. texture._bufferView = data;
  14654. texture.format = format;
  14655. texture.type = type;
  14656. texture.invertY = invertY;
  14657. texture._compression = compression;
  14658. }
  14659. if (texture.width % 4 !== 0) {
  14660. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14661. }
  14662. if (compression && data) {
  14663. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14664. }
  14665. else {
  14666. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14667. }
  14668. if (texture.generateMipMaps) {
  14669. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14670. }
  14671. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14672. // this.resetTextureCache();
  14673. texture.isReady = true;
  14674. };
  14675. /**
  14676. * Creates a raw texture
  14677. * @param data defines the data to store in the texture
  14678. * @param width defines the width of the texture
  14679. * @param height defines the height of the texture
  14680. * @param format defines the format of the data
  14681. * @param generateMipMaps defines if the engine should generate the mip levels
  14682. * @param invertY defines if data must be stored with Y axis inverted
  14683. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14684. * @param compression defines the compression used (null by default)
  14685. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14686. * @returns the raw texture inside an InternalTexture
  14687. */
  14688. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14689. if (compression === void 0) { compression = null; }
  14690. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14691. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14692. texture.baseWidth = width;
  14693. texture.baseHeight = height;
  14694. texture.width = width;
  14695. texture.height = height;
  14696. texture.format = format;
  14697. texture.generateMipMaps = generateMipMaps;
  14698. texture.samplingMode = samplingMode;
  14699. texture.invertY = invertY;
  14700. texture._compression = compression;
  14701. texture.type = type;
  14702. if (!this._doNotHandleContextLost) {
  14703. texture._bufferView = data;
  14704. }
  14705. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14706. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14707. // Filters
  14708. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14711. if (generateMipMaps) {
  14712. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14713. }
  14714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14715. this._internalTexturesCache.push(texture);
  14716. return texture;
  14717. };
  14718. /** @hidden */
  14719. Engine.prototype._unpackFlipY = function (value) {
  14720. if (this._unpackFlipYCached !== value) {
  14721. this._unpackFlipYCached = value;
  14722. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14723. }
  14724. };
  14725. /** @hidden */
  14726. Engine.prototype._getUnpackAlignement = function () {
  14727. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14728. };
  14729. /**
  14730. * Creates a dynamic texture
  14731. * @param width defines the width of the texture
  14732. * @param height defines the height of the texture
  14733. * @param generateMipMaps defines if the engine should generate the mip levels
  14734. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14735. * @returns the dynamic texture inside an InternalTexture
  14736. */
  14737. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14738. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14739. texture.baseWidth = width;
  14740. texture.baseHeight = height;
  14741. if (generateMipMaps) {
  14742. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14743. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14744. }
  14745. // this.resetTextureCache();
  14746. texture.width = width;
  14747. texture.height = height;
  14748. texture.isReady = false;
  14749. texture.generateMipMaps = generateMipMaps;
  14750. texture.samplingMode = samplingMode;
  14751. this.updateTextureSamplingMode(samplingMode, texture);
  14752. this._internalTexturesCache.push(texture);
  14753. return texture;
  14754. };
  14755. /**
  14756. * Update the sampling mode of a given texture
  14757. * @param samplingMode defines the required sampling mode
  14758. * @param texture defines the texture to update
  14759. */
  14760. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14761. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14762. if (texture.isCube) {
  14763. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14764. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14765. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14766. }
  14767. else if (texture.is3D) {
  14768. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14769. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14770. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14771. }
  14772. else {
  14773. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14774. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14775. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14776. }
  14777. texture.samplingMode = samplingMode;
  14778. };
  14779. /**
  14780. * Update the content of a dynamic texture
  14781. * @param texture defines the texture to update
  14782. * @param canvas defines the canvas containing the source
  14783. * @param invertY defines if data must be stored with Y axis inverted
  14784. * @param premulAlpha defines if alpha is stored as premultiplied
  14785. * @param format defines the format of the data
  14786. */
  14787. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14788. if (premulAlpha === void 0) { premulAlpha = false; }
  14789. if (!texture) {
  14790. return;
  14791. }
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14793. this._unpackFlipY(invertY);
  14794. if (premulAlpha) {
  14795. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14796. }
  14797. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14798. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14799. if (texture.generateMipMaps) {
  14800. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14801. }
  14802. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14803. if (premulAlpha) {
  14804. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14805. }
  14806. texture.isReady = true;
  14807. };
  14808. /**
  14809. * Update a video texture
  14810. * @param texture defines the texture to update
  14811. * @param video defines the video element to use
  14812. * @param invertY defines if data must be stored with Y axis inverted
  14813. */
  14814. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14815. if (!texture || texture._isDisabled) {
  14816. return;
  14817. }
  14818. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14819. this._unpackFlipY(!invertY); // Video are upside down by default
  14820. try {
  14821. // Testing video texture support
  14822. if (this._videoTextureSupported === undefined) {
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14824. if (this._gl.getError() !== 0) {
  14825. this._videoTextureSupported = false;
  14826. }
  14827. else {
  14828. this._videoTextureSupported = true;
  14829. }
  14830. }
  14831. // Copy video through the current working canvas if video texture is not supported
  14832. if (!this._videoTextureSupported) {
  14833. if (!texture._workingCanvas) {
  14834. texture._workingCanvas = document.createElement("canvas");
  14835. var context = texture._workingCanvas.getContext("2d");
  14836. if (!context) {
  14837. throw new Error("Unable to get 2d context");
  14838. }
  14839. texture._workingContext = context;
  14840. texture._workingCanvas.width = texture.width;
  14841. texture._workingCanvas.height = texture.height;
  14842. }
  14843. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14845. }
  14846. else {
  14847. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14848. }
  14849. if (texture.generateMipMaps) {
  14850. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14851. }
  14852. if (!wasPreviouslyBound) {
  14853. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14854. }
  14855. // this.resetTextureCache();
  14856. texture.isReady = true;
  14857. }
  14858. catch (ex) {
  14859. // Something unexpected
  14860. // Let's disable the texture
  14861. texture._isDisabled = true;
  14862. }
  14863. };
  14864. /**
  14865. * Updates a depth texture Comparison Mode and Function.
  14866. * If the comparison Function is equal to 0, the mode will be set to none.
  14867. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14868. * @param texture The texture to set the comparison function for
  14869. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14870. */
  14871. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14872. if (this.webGLVersion === 1) {
  14873. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14874. return;
  14875. }
  14876. var gl = this._gl;
  14877. if (texture.isCube) {
  14878. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14879. if (comparisonFunction === 0) {
  14880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14882. }
  14883. else {
  14884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14888. }
  14889. else {
  14890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14891. if (comparisonFunction === 0) {
  14892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14894. }
  14895. else {
  14896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14898. }
  14899. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14900. }
  14901. texture._comparisonFunction = comparisonFunction;
  14902. };
  14903. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14904. var width = size.width || size;
  14905. var height = size.height || size;
  14906. internalTexture.baseWidth = width;
  14907. internalTexture.baseHeight = height;
  14908. internalTexture.width = width;
  14909. internalTexture.height = height;
  14910. internalTexture.isReady = true;
  14911. internalTexture.samples = 1;
  14912. internalTexture.generateMipMaps = false;
  14913. internalTexture._generateDepthBuffer = true;
  14914. internalTexture._generateStencilBuffer = generateStencil;
  14915. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14916. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14917. internalTexture._comparisonFunction = comparisonFunction;
  14918. var gl = this._gl;
  14919. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14920. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14921. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14922. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14923. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14924. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14925. if (comparisonFunction === 0) {
  14926. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14927. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14928. }
  14929. else {
  14930. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14931. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14932. }
  14933. };
  14934. /**
  14935. * Creates a depth stencil texture.
  14936. * This is only available in WebGL 2 or with the depth texture extension available.
  14937. * @param size The size of face edge in the texture.
  14938. * @param options The options defining the texture.
  14939. * @returns The texture
  14940. */
  14941. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14942. if (options.isCube) {
  14943. var width = size.width || size;
  14944. return this._createDepthStencilCubeTexture(width, options);
  14945. }
  14946. else {
  14947. return this._createDepthStencilTexture(size, options);
  14948. }
  14949. };
  14950. /**
  14951. * Creates a depth stencil texture.
  14952. * This is only available in WebGL 2 or with the depth texture extension available.
  14953. * @param size The size of face edge in the texture.
  14954. * @param options The options defining the texture.
  14955. * @returns The texture
  14956. */
  14957. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14958. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14959. if (!this._caps.depthTextureExtension) {
  14960. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14961. return internalTexture;
  14962. }
  14963. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14964. var gl = this._gl;
  14965. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14966. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14967. if (this.webGLVersion > 1) {
  14968. if (internalOptions.generateStencil) {
  14969. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14970. }
  14971. else {
  14972. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14973. }
  14974. }
  14975. else {
  14976. if (internalOptions.generateStencil) {
  14977. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14978. }
  14979. else {
  14980. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14981. }
  14982. }
  14983. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14984. return internalTexture;
  14985. };
  14986. /**
  14987. * Creates a depth stencil cube texture.
  14988. * This is only available in WebGL 2.
  14989. * @param size The size of face edge in the cube texture.
  14990. * @param options The options defining the cube texture.
  14991. * @returns The cube texture
  14992. */
  14993. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14994. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14995. internalTexture.isCube = true;
  14996. if (this.webGLVersion === 1) {
  14997. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14998. return internalTexture;
  14999. }
  15000. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15001. var gl = this._gl;
  15002. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15003. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15004. // Create the depth/stencil buffer
  15005. for (var face = 0; face < 6; face++) {
  15006. if (internalOptions.generateStencil) {
  15007. 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);
  15008. }
  15009. else {
  15010. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15011. }
  15012. }
  15013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15014. return internalTexture;
  15015. };
  15016. /**
  15017. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15018. * @param renderTarget The render target to set the frame buffer for
  15019. */
  15020. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15021. // Create the framebuffer
  15022. var internalTexture = renderTarget.getInternalTexture();
  15023. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15024. return;
  15025. }
  15026. var gl = this._gl;
  15027. var depthStencilTexture = renderTarget.depthStencilTexture;
  15028. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15029. if (depthStencilTexture.isCube) {
  15030. if (depthStencilTexture._generateStencilBuffer) {
  15031. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15032. }
  15033. else {
  15034. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15035. }
  15036. }
  15037. else {
  15038. if (depthStencilTexture._generateStencilBuffer) {
  15039. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15040. }
  15041. else {
  15042. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15043. }
  15044. }
  15045. this.bindUnboundFramebuffer(null);
  15046. };
  15047. /**
  15048. * Creates a new render target texture
  15049. * @param size defines the size of the texture
  15050. * @param options defines the options used to create the texture
  15051. * @returns a new render target texture stored in an InternalTexture
  15052. */
  15053. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15054. var fullOptions = new RenderTargetCreationOptions();
  15055. if (options !== undefined && typeof options === "object") {
  15056. fullOptions.generateMipMaps = options.generateMipMaps;
  15057. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15058. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15059. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15060. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15061. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15062. }
  15063. else {
  15064. fullOptions.generateMipMaps = options;
  15065. fullOptions.generateDepthBuffer = true;
  15066. fullOptions.generateStencilBuffer = false;
  15067. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15068. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15069. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15070. }
  15071. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15072. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15073. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15074. }
  15075. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15076. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15077. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15078. }
  15079. var gl = this._gl;
  15080. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15081. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15082. var width = size.width || size;
  15083. var height = size.height || size;
  15084. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15085. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15086. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15087. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15088. }
  15089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15093. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15094. // Create the framebuffer
  15095. var currentFrameBuffer = this._currentFramebuffer;
  15096. var framebuffer = gl.createFramebuffer();
  15097. this.bindUnboundFramebuffer(framebuffer);
  15098. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15099. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15100. if (fullOptions.generateMipMaps) {
  15101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15102. }
  15103. // Unbind
  15104. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15105. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15106. this.bindUnboundFramebuffer(currentFrameBuffer);
  15107. texture._framebuffer = framebuffer;
  15108. texture.baseWidth = width;
  15109. texture.baseHeight = height;
  15110. texture.width = width;
  15111. texture.height = height;
  15112. texture.isReady = true;
  15113. texture.samples = 1;
  15114. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15115. texture.samplingMode = fullOptions.samplingMode;
  15116. texture.type = fullOptions.type;
  15117. texture.format = fullOptions.format;
  15118. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15119. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15120. // this.resetTextureCache();
  15121. this._internalTexturesCache.push(texture);
  15122. return texture;
  15123. };
  15124. /**
  15125. * Create a multi render target texture
  15126. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15127. * @param size defines the size of the texture
  15128. * @param options defines the creation options
  15129. * @returns the cube texture as an InternalTexture
  15130. */
  15131. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15132. var generateMipMaps = false;
  15133. var generateDepthBuffer = true;
  15134. var generateStencilBuffer = false;
  15135. var generateDepthTexture = false;
  15136. var textureCount = 1;
  15137. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15138. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15139. var types = new Array();
  15140. var samplingModes = new Array();
  15141. if (options !== undefined) {
  15142. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15143. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15144. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15145. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15146. textureCount = options.textureCount || 1;
  15147. if (options.types) {
  15148. types = options.types;
  15149. }
  15150. if (options.samplingModes) {
  15151. samplingModes = options.samplingModes;
  15152. }
  15153. }
  15154. var gl = this._gl;
  15155. // Create the framebuffer
  15156. var framebuffer = gl.createFramebuffer();
  15157. this.bindUnboundFramebuffer(framebuffer);
  15158. var width = size.width || size;
  15159. var height = size.height || size;
  15160. var textures = [];
  15161. var attachments = [];
  15162. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15163. for (var i = 0; i < textureCount; i++) {
  15164. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15165. var type = types[i] || defaultType;
  15166. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15167. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15168. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15169. }
  15170. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15171. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15172. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15173. }
  15174. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15175. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15176. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15177. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15178. }
  15179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15180. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15181. textures.push(texture);
  15182. attachments.push(attachment);
  15183. gl.activeTexture(gl["TEXTURE" + i]);
  15184. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15189. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15190. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15191. if (generateMipMaps) {
  15192. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15193. }
  15194. // Unbind
  15195. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15196. texture._framebuffer = framebuffer;
  15197. texture._depthStencilBuffer = depthStencilBuffer;
  15198. texture.baseWidth = width;
  15199. texture.baseHeight = height;
  15200. texture.width = width;
  15201. texture.height = height;
  15202. texture.isReady = true;
  15203. texture.samples = 1;
  15204. texture.generateMipMaps = generateMipMaps;
  15205. texture.samplingMode = samplingMode;
  15206. texture.type = type;
  15207. texture._generateDepthBuffer = generateDepthBuffer;
  15208. texture._generateStencilBuffer = generateStencilBuffer;
  15209. texture._attachments = attachments;
  15210. this._internalTexturesCache.push(texture);
  15211. }
  15212. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15213. // Depth texture
  15214. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15215. gl.activeTexture(gl.TEXTURE0);
  15216. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15221. 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);
  15222. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15223. depthTexture._framebuffer = framebuffer;
  15224. depthTexture.baseWidth = width;
  15225. depthTexture.baseHeight = height;
  15226. depthTexture.width = width;
  15227. depthTexture.height = height;
  15228. depthTexture.isReady = true;
  15229. depthTexture.samples = 1;
  15230. depthTexture.generateMipMaps = generateMipMaps;
  15231. depthTexture.samplingMode = gl.NEAREST;
  15232. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15233. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15234. textures.push(depthTexture);
  15235. this._internalTexturesCache.push(depthTexture);
  15236. }
  15237. gl.drawBuffers(attachments);
  15238. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15239. this.bindUnboundFramebuffer(null);
  15240. this.resetTextureCache();
  15241. return textures;
  15242. };
  15243. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15244. if (samples === void 0) { samples = 1; }
  15245. var depthStencilBuffer = null;
  15246. var gl = this._gl;
  15247. // Create the depth/stencil buffer
  15248. if (generateStencilBuffer) {
  15249. depthStencilBuffer = gl.createRenderbuffer();
  15250. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15251. if (samples > 1) {
  15252. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15253. }
  15254. else {
  15255. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15256. }
  15257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15258. }
  15259. else if (generateDepthBuffer) {
  15260. depthStencilBuffer = gl.createRenderbuffer();
  15261. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15262. if (samples > 1) {
  15263. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15264. }
  15265. else {
  15266. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15267. }
  15268. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15269. }
  15270. return depthStencilBuffer;
  15271. };
  15272. /**
  15273. * Updates the sample count of a render target texture
  15274. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15275. * @param texture defines the texture to update
  15276. * @param samples defines the sample count to set
  15277. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15278. */
  15279. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15280. if (this.webGLVersion < 2 || !texture) {
  15281. return 1;
  15282. }
  15283. if (texture.samples === samples) {
  15284. return samples;
  15285. }
  15286. var gl = this._gl;
  15287. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15288. // Dispose previous render buffers
  15289. if (texture._depthStencilBuffer) {
  15290. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15291. texture._depthStencilBuffer = null;
  15292. }
  15293. if (texture._MSAAFramebuffer) {
  15294. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15295. texture._MSAAFramebuffer = null;
  15296. }
  15297. if (texture._MSAARenderBuffer) {
  15298. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15299. texture._MSAARenderBuffer = null;
  15300. }
  15301. if (samples > 1) {
  15302. var framebuffer = gl.createFramebuffer();
  15303. if (!framebuffer) {
  15304. throw new Error("Unable to create multi sampled framebuffer");
  15305. }
  15306. texture._MSAAFramebuffer = framebuffer;
  15307. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15308. var colorRenderbuffer = gl.createRenderbuffer();
  15309. if (!colorRenderbuffer) {
  15310. throw new Error("Unable to create multi sampled framebuffer");
  15311. }
  15312. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15313. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15314. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15315. texture._MSAARenderBuffer = colorRenderbuffer;
  15316. }
  15317. else {
  15318. this.bindUnboundFramebuffer(texture._framebuffer);
  15319. }
  15320. texture.samples = samples;
  15321. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15322. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15323. this.bindUnboundFramebuffer(null);
  15324. return samples;
  15325. };
  15326. /**
  15327. * Update the sample count for a given multiple render target texture
  15328. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15329. * @param textures defines the textures to update
  15330. * @param samples defines the sample count to set
  15331. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15332. */
  15333. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15334. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15335. return 1;
  15336. }
  15337. if (textures[0].samples === samples) {
  15338. return samples;
  15339. }
  15340. var gl = this._gl;
  15341. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15342. // Dispose previous render buffers
  15343. if (textures[0]._depthStencilBuffer) {
  15344. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15345. textures[0]._depthStencilBuffer = null;
  15346. }
  15347. if (textures[0]._MSAAFramebuffer) {
  15348. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15349. textures[0]._MSAAFramebuffer = null;
  15350. }
  15351. for (var i = 0; i < textures.length; i++) {
  15352. if (textures[i]._MSAARenderBuffer) {
  15353. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15354. textures[i]._MSAARenderBuffer = null;
  15355. }
  15356. }
  15357. if (samples > 1) {
  15358. var framebuffer = gl.createFramebuffer();
  15359. if (!framebuffer) {
  15360. throw new Error("Unable to create multi sampled framebuffer");
  15361. }
  15362. this.bindUnboundFramebuffer(framebuffer);
  15363. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15364. var attachments = [];
  15365. for (var i = 0; i < textures.length; i++) {
  15366. var texture = textures[i];
  15367. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15368. var colorRenderbuffer = gl.createRenderbuffer();
  15369. if (!colorRenderbuffer) {
  15370. throw new Error("Unable to create multi sampled framebuffer");
  15371. }
  15372. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15373. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15374. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15375. texture._MSAAFramebuffer = framebuffer;
  15376. texture._MSAARenderBuffer = colorRenderbuffer;
  15377. texture.samples = samples;
  15378. texture._depthStencilBuffer = depthStencilBuffer;
  15379. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15380. attachments.push(attachment);
  15381. }
  15382. gl.drawBuffers(attachments);
  15383. }
  15384. else {
  15385. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15386. }
  15387. this.bindUnboundFramebuffer(null);
  15388. return samples;
  15389. };
  15390. /** @hidden */
  15391. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15392. if (faceIndex === void 0) { faceIndex = 0; }
  15393. if (lod === void 0) { lod = 0; }
  15394. var gl = this._gl;
  15395. var target = gl.TEXTURE_2D;
  15396. if (texture.isCube) {
  15397. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15398. }
  15399. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15400. };
  15401. /** @hidden */
  15402. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15403. if (faceIndex === void 0) { faceIndex = 0; }
  15404. if (lod === void 0) { lod = 0; }
  15405. var gl = this._gl;
  15406. var textureType = this._getWebGLTextureType(texture.type);
  15407. var format = this._getInternalFormat(texture.format);
  15408. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15409. this._unpackFlipY(texture.invertY);
  15410. var target = gl.TEXTURE_2D;
  15411. if (texture.isCube) {
  15412. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15413. }
  15414. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15415. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15416. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15417. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15418. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15419. };
  15420. /** @hidden */
  15421. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15422. if (faceIndex === void 0) { faceIndex = 0; }
  15423. if (lod === void 0) { lod = 0; }
  15424. var gl = this._gl;
  15425. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15426. this._bindTextureDirectly(bindTarget, texture, true);
  15427. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15428. this._bindTextureDirectly(bindTarget, null, true);
  15429. };
  15430. /** @hidden */
  15431. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15432. if (faceIndex === void 0) { faceIndex = 0; }
  15433. if (lod === void 0) { lod = 0; }
  15434. var gl = this._gl;
  15435. var textureType = this._getWebGLTextureType(texture.type);
  15436. var format = this._getInternalFormat(texture.format);
  15437. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15438. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15439. this._bindTextureDirectly(bindTarget, texture, true);
  15440. this._unpackFlipY(texture.invertY);
  15441. var target = gl.TEXTURE_2D;
  15442. if (texture.isCube) {
  15443. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15444. }
  15445. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15446. this._bindTextureDirectly(bindTarget, null, true);
  15447. };
  15448. /**
  15449. * Creates a new render target cube texture
  15450. * @param size defines the size of the texture
  15451. * @param options defines the options used to create the texture
  15452. * @returns a new render target cube texture stored in an InternalTexture
  15453. */
  15454. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15455. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15456. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15457. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15458. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15459. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15460. }
  15461. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15462. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15463. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15464. }
  15465. var gl = this._gl;
  15466. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15467. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15468. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15469. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15470. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15471. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15472. }
  15473. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15477. for (var face = 0; face < 6; face++) {
  15478. 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);
  15479. }
  15480. // Create the framebuffer
  15481. var framebuffer = gl.createFramebuffer();
  15482. this.bindUnboundFramebuffer(framebuffer);
  15483. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15484. // MipMaps
  15485. if (fullOptions.generateMipMaps) {
  15486. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15487. }
  15488. // Unbind
  15489. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15490. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15491. this.bindUnboundFramebuffer(null);
  15492. texture._framebuffer = framebuffer;
  15493. texture.width = size;
  15494. texture.height = size;
  15495. texture.isReady = true;
  15496. texture.isCube = true;
  15497. texture.samples = 1;
  15498. texture.generateMipMaps = fullOptions.generateMipMaps;
  15499. texture.samplingMode = fullOptions.samplingMode;
  15500. texture.type = fullOptions.type;
  15501. texture.format = fullOptions.format;
  15502. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15503. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15504. this._internalTexturesCache.push(texture);
  15505. return texture;
  15506. };
  15507. /**
  15508. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15509. * @param rootUrl defines the url where the file to load is located
  15510. * @param scene defines the current scene
  15511. * @param lodScale defines scale to apply to the mip map selection
  15512. * @param lodOffset defines offset to apply to the mip map selection
  15513. * @param onLoad defines an optional callback raised when the texture is loaded
  15514. * @param onError defines an optional callback raised if there is an issue to load the texture
  15515. * @param format defines the format of the data
  15516. * @param forcedExtension defines the extension to use to pick the right loader
  15517. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15518. * @returns the cube texture as an InternalTexture
  15519. */
  15520. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15521. var _this = this;
  15522. if (onLoad === void 0) { onLoad = null; }
  15523. if (onError === void 0) { onError = null; }
  15524. if (forcedExtension === void 0) { forcedExtension = null; }
  15525. if (createPolynomials === void 0) { createPolynomials = true; }
  15526. var callback = function (loadData) {
  15527. if (!loadData) {
  15528. if (onLoad) {
  15529. onLoad(null);
  15530. }
  15531. return;
  15532. }
  15533. var texture = loadData.texture;
  15534. if (!createPolynomials) {
  15535. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15536. }
  15537. else if (loadData.info.sphericalPolynomial) {
  15538. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15539. }
  15540. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15541. if (_this._caps.textureLOD) {
  15542. // Do not add extra process if texture lod is supported.
  15543. if (onLoad) {
  15544. onLoad(texture);
  15545. }
  15546. return;
  15547. }
  15548. var mipSlices = 3;
  15549. var gl = _this._gl;
  15550. var width = loadData.width;
  15551. if (!width) {
  15552. return;
  15553. }
  15554. var textures = [];
  15555. for (var i = 0; i < mipSlices; i++) {
  15556. //compute LOD from even spacing in smoothness (matching shader calculation)
  15557. var smoothness = i / (mipSlices - 1);
  15558. var roughness = 1 - smoothness;
  15559. var minLODIndex = lodOffset; // roughness = 0
  15560. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15561. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15562. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15563. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15564. glTextureFromLod.type = texture.type;
  15565. glTextureFromLod.format = texture.format;
  15566. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15567. glTextureFromLod.height = glTextureFromLod.width;
  15568. glTextureFromLod.isCube = true;
  15569. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15574. if (loadData.isDDS) {
  15575. var info = loadData.info;
  15576. var data = loadData.data;
  15577. _this._unpackFlipY(info.isCompressed);
  15578. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15579. }
  15580. else {
  15581. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15582. }
  15583. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15584. // Wrap in a base texture for easy binding.
  15585. var lodTexture = new BABYLON.BaseTexture(scene);
  15586. lodTexture.isCube = true;
  15587. lodTexture._texture = glTextureFromLod;
  15588. glTextureFromLod.isReady = true;
  15589. textures.push(lodTexture);
  15590. }
  15591. texture._lodTextureHigh = textures[2];
  15592. texture._lodTextureMid = textures[1];
  15593. texture._lodTextureLow = textures[0];
  15594. if (onLoad) {
  15595. onLoad(texture);
  15596. }
  15597. };
  15598. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15599. };
  15600. /**
  15601. * Creates a cube texture
  15602. * @param rootUrl defines the url where the files to load is located
  15603. * @param scene defines the current scene
  15604. * @param files defines the list of files to load (1 per face)
  15605. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15606. * @param onLoad defines an optional callback raised when the texture is loaded
  15607. * @param onError defines an optional callback raised if there is an issue to load the texture
  15608. * @param format defines the format of the data
  15609. * @param forcedExtension defines the extension to use to pick the right loader
  15610. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15611. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15612. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15613. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15614. * @returns the cube texture as an InternalTexture
  15615. */
  15616. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15617. var _this = this;
  15618. if (onLoad === void 0) { onLoad = null; }
  15619. if (onError === void 0) { onError = null; }
  15620. if (forcedExtension === void 0) { forcedExtension = null; }
  15621. if (createPolynomials === void 0) { createPolynomials = false; }
  15622. if (lodScale === void 0) { lodScale = 0; }
  15623. if (lodOffset === void 0) { lodOffset = 0; }
  15624. if (fallback === void 0) { fallback = null; }
  15625. var gl = this._gl;
  15626. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15627. texture.isCube = true;
  15628. texture.url = rootUrl;
  15629. texture.generateMipMaps = !noMipmap;
  15630. texture._lodGenerationScale = lodScale;
  15631. texture._lodGenerationOffset = lodOffset;
  15632. if (!this._doNotHandleContextLost) {
  15633. texture._extension = forcedExtension;
  15634. texture._files = files;
  15635. }
  15636. var lastDot = rootUrl.lastIndexOf('.');
  15637. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15638. var loader = null;
  15639. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15640. var availableLoader = _a[_i];
  15641. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15642. loader = availableLoader;
  15643. break;
  15644. }
  15645. }
  15646. var onInternalError = function (request, exception) {
  15647. if (loader) {
  15648. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15649. if (fallbackUrl) {
  15650. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15651. }
  15652. }
  15653. if (onError && request) {
  15654. onError(request.status + " " + request.statusText, exception);
  15655. }
  15656. };
  15657. if (loader) {
  15658. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15659. var onloaddata = function (data) {
  15660. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15661. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15662. };
  15663. if (files && files.length === 6) {
  15664. if (loader.supportCascades) {
  15665. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15666. }
  15667. else if (onError) {
  15668. onError("Textures type does not support cascades.");
  15669. }
  15670. }
  15671. else {
  15672. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15673. }
  15674. }
  15675. else {
  15676. if (!files) {
  15677. throw new Error("Cannot load cubemap because files were not defined");
  15678. }
  15679. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15680. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15681. var height = width;
  15682. _this._prepareWorkingCanvas();
  15683. if (!_this._workingCanvas || !_this._workingContext) {
  15684. return;
  15685. }
  15686. _this._workingCanvas.width = width;
  15687. _this._workingCanvas.height = height;
  15688. var faces = [
  15689. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15690. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15691. ];
  15692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15693. _this._unpackFlipY(false);
  15694. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15695. for (var index = 0; index < faces.length; index++) {
  15696. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15697. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15698. }
  15699. if (!noMipmap) {
  15700. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15701. }
  15702. _this._setCubeMapTextureParams(!noMipmap);
  15703. texture.width = width;
  15704. texture.height = height;
  15705. texture.isReady = true;
  15706. if (format) {
  15707. texture.format = format;
  15708. }
  15709. texture.onLoadedObservable.notifyObservers(texture);
  15710. texture.onLoadedObservable.clear();
  15711. if (onLoad) {
  15712. onLoad();
  15713. }
  15714. }, files, onError);
  15715. }
  15716. this._internalTexturesCache.push(texture);
  15717. return texture;
  15718. };
  15719. /**
  15720. * @hidden
  15721. */
  15722. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15723. var gl = this._gl;
  15724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15728. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15729. // this.resetTextureCache();
  15730. };
  15731. /**
  15732. * Update a raw cube texture
  15733. * @param texture defines the texture to udpdate
  15734. * @param data defines the data to store
  15735. * @param format defines the data format
  15736. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15737. * @param invertY defines if data must be stored with Y axis inverted
  15738. * @param compression defines the compression used (null by default)
  15739. * @param level defines which level of the texture to update
  15740. */
  15741. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15742. if (compression === void 0) { compression = null; }
  15743. if (level === void 0) { level = 0; }
  15744. texture._bufferViewArray = data;
  15745. texture.format = format;
  15746. texture.type = type;
  15747. texture.invertY = invertY;
  15748. texture._compression = compression;
  15749. var gl = this._gl;
  15750. var textureType = this._getWebGLTextureType(type);
  15751. var internalFormat = this._getInternalFormat(format);
  15752. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15753. var needConversion = false;
  15754. if (internalFormat === gl.RGB) {
  15755. internalFormat = gl.RGBA;
  15756. needConversion = true;
  15757. }
  15758. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15759. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15760. if (texture.width % 4 !== 0) {
  15761. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15762. }
  15763. // Data are known to be in +X +Y +Z -X -Y -Z
  15764. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15765. var faceData = data[faceIndex];
  15766. if (compression) {
  15767. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15768. }
  15769. else {
  15770. if (needConversion) {
  15771. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15772. }
  15773. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15774. }
  15775. }
  15776. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15777. if (isPot && texture.generateMipMaps && level === 0) {
  15778. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15779. }
  15780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15781. // this.resetTextureCache();
  15782. texture.isReady = true;
  15783. };
  15784. /**
  15785. * Creates a new raw cube texture
  15786. * @param data defines the array of data to use to create each face
  15787. * @param size defines the size of the textures
  15788. * @param format defines the format of the data
  15789. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15790. * @param generateMipMaps defines if the engine should generate the mip levels
  15791. * @param invertY defines if data must be stored with Y axis inverted
  15792. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15793. * @param compression defines the compression used (null by default)
  15794. * @returns the cube texture as an InternalTexture
  15795. */
  15796. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15797. if (compression === void 0) { compression = null; }
  15798. var gl = this._gl;
  15799. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15800. texture.isCube = true;
  15801. texture.format = format;
  15802. texture.type = type;
  15803. if (!this._doNotHandleContextLost) {
  15804. texture._bufferViewArray = data;
  15805. }
  15806. var textureType = this._getWebGLTextureType(type);
  15807. var internalFormat = this._getInternalFormat(format);
  15808. if (internalFormat === gl.RGB) {
  15809. internalFormat = gl.RGBA;
  15810. }
  15811. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15812. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15813. generateMipMaps = false;
  15814. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15815. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15816. }
  15817. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15818. generateMipMaps = false;
  15819. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15820. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15821. }
  15822. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15823. generateMipMaps = false;
  15824. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15825. }
  15826. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15827. generateMipMaps = false;
  15828. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15829. }
  15830. var width = size;
  15831. var height = width;
  15832. texture.width = width;
  15833. texture.height = height;
  15834. // Double check on POT to generate Mips.
  15835. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15836. if (!isPot) {
  15837. generateMipMaps = false;
  15838. }
  15839. // Upload data if needed. The texture won't be ready until then.
  15840. if (data) {
  15841. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15842. }
  15843. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15844. // Filters
  15845. if (data && generateMipMaps) {
  15846. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15847. }
  15848. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15853. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15854. texture.generateMipMaps = generateMipMaps;
  15855. return texture;
  15856. };
  15857. /**
  15858. * Creates a new raw cube texture from a specified url
  15859. * @param url defines the url where the data is located
  15860. * @param scene defines the current scene
  15861. * @param size defines the size of the textures
  15862. * @param format defines the format of the data
  15863. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15864. * @param noMipmap defines if the engine should avoid generating the mip levels
  15865. * @param callback defines a callback used to extract texture data from loaded data
  15866. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15867. * @param onLoad defines a callback called when texture is loaded
  15868. * @param onError defines a callback called if there is an error
  15869. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15870. * @param invertY defines if data must be stored with Y axis inverted
  15871. * @returns the cube texture as an InternalTexture
  15872. */
  15873. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15874. var _this = this;
  15875. if (onLoad === void 0) { onLoad = null; }
  15876. if (onError === void 0) { onError = null; }
  15877. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15878. if (invertY === void 0) { invertY = false; }
  15879. var gl = this._gl;
  15880. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15881. scene._addPendingData(texture);
  15882. texture.url = url;
  15883. this._internalTexturesCache.push(texture);
  15884. var onerror = function (request, exception) {
  15885. scene._removePendingData(texture);
  15886. if (onError && request) {
  15887. onError(request.status + " " + request.statusText, exception);
  15888. }
  15889. };
  15890. var internalCallback = function (data) {
  15891. var width = texture.width;
  15892. var faceDataArrays = callback(data);
  15893. if (!faceDataArrays) {
  15894. return;
  15895. }
  15896. if (mipmapGenerator) {
  15897. var textureType = _this._getWebGLTextureType(type);
  15898. var internalFormat = _this._getInternalFormat(format);
  15899. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15900. var needConversion = false;
  15901. if (internalFormat === gl.RGB) {
  15902. internalFormat = gl.RGBA;
  15903. needConversion = true;
  15904. }
  15905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15906. _this._unpackFlipY(false);
  15907. var mipData = mipmapGenerator(faceDataArrays);
  15908. for (var level = 0; level < mipData.length; level++) {
  15909. var mipSize = width >> level;
  15910. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15911. var mipFaceData = mipData[level][faceIndex];
  15912. if (needConversion) {
  15913. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15914. }
  15915. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15916. }
  15917. }
  15918. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15919. }
  15920. else {
  15921. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15922. }
  15923. texture.isReady = true;
  15924. // this.resetTextureCache();
  15925. scene._removePendingData(texture);
  15926. if (onLoad) {
  15927. onLoad();
  15928. }
  15929. };
  15930. this._loadFile(url, function (data) {
  15931. internalCallback(data);
  15932. }, undefined, scene.database, true, onerror);
  15933. return texture;
  15934. };
  15935. ;
  15936. /**
  15937. * Update a raw 3D texture
  15938. * @param texture defines the texture to update
  15939. * @param data defines the data to store
  15940. * @param format defines the data format
  15941. * @param invertY defines if data must be stored with Y axis inverted
  15942. * @param compression defines the used compression (can be null)
  15943. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15944. */
  15945. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15946. if (compression === void 0) { compression = null; }
  15947. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15948. var internalType = this._getWebGLTextureType(textureType);
  15949. var internalFormat = this._getInternalFormat(format);
  15950. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15951. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15952. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15953. if (!this._doNotHandleContextLost) {
  15954. texture._bufferView = data;
  15955. texture.format = format;
  15956. texture.invertY = invertY;
  15957. texture._compression = compression;
  15958. }
  15959. if (texture.width % 4 !== 0) {
  15960. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15961. }
  15962. if (compression && data) {
  15963. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15964. }
  15965. else {
  15966. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15967. }
  15968. if (texture.generateMipMaps) {
  15969. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15970. }
  15971. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15972. // this.resetTextureCache();
  15973. texture.isReady = true;
  15974. };
  15975. /**
  15976. * Creates a new raw 3D texture
  15977. * @param data defines the data used to create the texture
  15978. * @param width defines the width of the texture
  15979. * @param height defines the height of the texture
  15980. * @param depth defines the depth of the texture
  15981. * @param format defines the format of the texture
  15982. * @param generateMipMaps defines if the engine must generate mip levels
  15983. * @param invertY defines if data must be stored with Y axis inverted
  15984. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15985. * @param compression defines the compressed used (can be null)
  15986. * @param textureType defines the compressed used (can be null)
  15987. * @returns a new raw 3D texture (stored in an InternalTexture)
  15988. */
  15989. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15990. if (compression === void 0) { compression = null; }
  15991. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15992. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15993. texture.baseWidth = width;
  15994. texture.baseHeight = height;
  15995. texture.baseDepth = depth;
  15996. texture.width = width;
  15997. texture.height = height;
  15998. texture.depth = depth;
  15999. texture.format = format;
  16000. texture.type = textureType;
  16001. texture.generateMipMaps = generateMipMaps;
  16002. texture.samplingMode = samplingMode;
  16003. texture.is3D = true;
  16004. if (!this._doNotHandleContextLost) {
  16005. texture._bufferView = data;
  16006. }
  16007. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16008. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16009. // Filters
  16010. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16011. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16012. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16013. if (generateMipMaps) {
  16014. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16015. }
  16016. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16017. this._internalTexturesCache.push(texture);
  16018. return texture;
  16019. };
  16020. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16021. var gl = this._gl;
  16022. if (!gl) {
  16023. return;
  16024. }
  16025. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16026. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16027. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16028. if (!noMipmap && !isCompressed) {
  16029. gl.generateMipmap(gl.TEXTURE_2D);
  16030. }
  16031. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16032. // this.resetTextureCache();
  16033. if (scene) {
  16034. scene._removePendingData(texture);
  16035. }
  16036. texture.onLoadedObservable.notifyObservers(texture);
  16037. texture.onLoadedObservable.clear();
  16038. };
  16039. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16040. var _this = this;
  16041. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16042. var maxTextureSize = this.getCaps().maxTextureSize;
  16043. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16044. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16045. var gl = this._gl;
  16046. if (!gl) {
  16047. return;
  16048. }
  16049. if (!texture._webGLTexture) {
  16050. // this.resetTextureCache();
  16051. if (scene) {
  16052. scene._removePendingData(texture);
  16053. }
  16054. return;
  16055. }
  16056. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16057. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16058. texture.baseWidth = width;
  16059. texture.baseHeight = height;
  16060. texture.width = potWidth;
  16061. texture.height = potHeight;
  16062. texture.isReady = true;
  16063. if (processFunction(potWidth, potHeight, function () {
  16064. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16065. })) {
  16066. // Returning as texture needs extra async steps
  16067. return;
  16068. }
  16069. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16070. };
  16071. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16072. // Create new RGBA data container.
  16073. var rgbaData;
  16074. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16075. rgbaData = new Float32Array(width * height * 4);
  16076. }
  16077. else {
  16078. rgbaData = new Uint32Array(width * height * 4);
  16079. }
  16080. // Convert each pixel.
  16081. for (var x = 0; x < width; x++) {
  16082. for (var y = 0; y < height; y++) {
  16083. var index = (y * width + x) * 3;
  16084. var newIndex = (y * width + x) * 4;
  16085. // Map Old Value to new value.
  16086. rgbaData[newIndex + 0] = rgbData[index + 0];
  16087. rgbaData[newIndex + 1] = rgbData[index + 1];
  16088. rgbaData[newIndex + 2] = rgbData[index + 2];
  16089. // Add fully opaque alpha channel.
  16090. rgbaData[newIndex + 3] = 1;
  16091. }
  16092. }
  16093. return rgbaData;
  16094. };
  16095. /** @hidden */
  16096. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16097. var gl = this._gl;
  16098. if (texture._framebuffer) {
  16099. gl.deleteFramebuffer(texture._framebuffer);
  16100. texture._framebuffer = null;
  16101. }
  16102. if (texture._depthStencilBuffer) {
  16103. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16104. texture._depthStencilBuffer = null;
  16105. }
  16106. if (texture._MSAAFramebuffer) {
  16107. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16108. texture._MSAAFramebuffer = null;
  16109. }
  16110. if (texture._MSAARenderBuffer) {
  16111. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16112. texture._MSAARenderBuffer = null;
  16113. }
  16114. };
  16115. /** @hidden */
  16116. Engine.prototype._releaseTexture = function (texture) {
  16117. var gl = this._gl;
  16118. this._releaseFramebufferObjects(texture);
  16119. gl.deleteTexture(texture._webGLTexture);
  16120. // Unbind channels
  16121. this.unbindAllTextures();
  16122. var index = this._internalTexturesCache.indexOf(texture);
  16123. if (index !== -1) {
  16124. this._internalTexturesCache.splice(index, 1);
  16125. }
  16126. // Integrated fixed lod samplers.
  16127. if (texture._lodTextureHigh) {
  16128. texture._lodTextureHigh.dispose();
  16129. }
  16130. if (texture._lodTextureMid) {
  16131. texture._lodTextureMid.dispose();
  16132. }
  16133. if (texture._lodTextureLow) {
  16134. texture._lodTextureLow.dispose();
  16135. }
  16136. // Set output texture of post process to null if the texture has been released/disposed
  16137. this.scenes.forEach(function (scene) {
  16138. scene.postProcesses.forEach(function (postProcess) {
  16139. if (postProcess._outputTexture == texture) {
  16140. postProcess._outputTexture = null;
  16141. }
  16142. });
  16143. scene.cameras.forEach(function (camera) {
  16144. camera._postProcesses.forEach(function (postProcess) {
  16145. if (postProcess) {
  16146. if (postProcess._outputTexture == texture) {
  16147. postProcess._outputTexture = null;
  16148. }
  16149. }
  16150. });
  16151. });
  16152. });
  16153. };
  16154. Engine.prototype.setProgram = function (program) {
  16155. if (this._currentProgram !== program) {
  16156. this._gl.useProgram(program);
  16157. this._currentProgram = program;
  16158. }
  16159. };
  16160. /**
  16161. * Binds an effect to the webGL context
  16162. * @param effect defines the effect to bind
  16163. */
  16164. Engine.prototype.bindSamplers = function (effect) {
  16165. this.setProgram(effect.getProgram());
  16166. var samplers = effect.getSamplers();
  16167. for (var index = 0; index < samplers.length; index++) {
  16168. var uniform = effect.getUniform(samplers[index]);
  16169. if (uniform) {
  16170. this._boundUniforms[index] = uniform;
  16171. }
  16172. }
  16173. this._currentEffect = null;
  16174. };
  16175. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16176. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16177. return;
  16178. }
  16179. // Remove
  16180. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16181. // Bind last to it
  16182. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16183. // Bind to dummy
  16184. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16185. };
  16186. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16187. if (!internalTexture) {
  16188. return -1;
  16189. }
  16190. internalTexture._initialSlot = channel;
  16191. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16192. if (channel !== internalTexture._designatedSlot) {
  16193. this._textureCollisions.addCount(1, false);
  16194. }
  16195. }
  16196. else {
  16197. if (channel !== internalTexture._designatedSlot) {
  16198. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16199. return internalTexture._designatedSlot;
  16200. }
  16201. else {
  16202. // No slot for this texture, let's pick a new one (if we find a free slot)
  16203. if (this._nextFreeTextureSlots.length) {
  16204. return this._nextFreeTextureSlots[0];
  16205. }
  16206. // We need to recycle the oldest bound texture, sorry.
  16207. this._textureCollisions.addCount(1, false);
  16208. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16209. }
  16210. }
  16211. }
  16212. return channel;
  16213. };
  16214. Engine.prototype._linkTrackers = function (previous, next) {
  16215. previous.next = next;
  16216. next.previous = previous;
  16217. };
  16218. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16219. var currentSlot = internalTexture._designatedSlot;
  16220. if (currentSlot === -1) {
  16221. return -1;
  16222. }
  16223. internalTexture._designatedSlot = -1;
  16224. if (this.disableTextureBindingOptimization) {
  16225. return -1;
  16226. }
  16227. // Remove from bound list
  16228. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16229. // Free the slot
  16230. this._boundTexturesCache[currentSlot] = null;
  16231. this._nextFreeTextureSlots.push(currentSlot);
  16232. return currentSlot;
  16233. };
  16234. Engine.prototype._activateCurrentTexture = function () {
  16235. if (this._currentTextureChannel !== this._activeChannel) {
  16236. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16237. this._currentTextureChannel = this._activeChannel;
  16238. }
  16239. };
  16240. /** @hidden */
  16241. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16242. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16243. if (force === void 0) { force = false; }
  16244. var wasPreviouslyBound = false;
  16245. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16246. this._activeChannel = texture._designatedSlot;
  16247. }
  16248. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16249. var isTextureForRendering = texture && texture._initialSlot > -1;
  16250. if (currentTextureBound !== texture || force) {
  16251. if (currentTextureBound) {
  16252. this._removeDesignatedSlot(currentTextureBound);
  16253. }
  16254. this._activateCurrentTexture();
  16255. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16256. this._boundTexturesCache[this._activeChannel] = texture;
  16257. if (texture) {
  16258. if (!this.disableTextureBindingOptimization) {
  16259. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16260. if (slotIndex > -1) {
  16261. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16262. }
  16263. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16264. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16265. }
  16266. texture._designatedSlot = this._activeChannel;
  16267. }
  16268. }
  16269. else if (forTextureDataUpdate) {
  16270. wasPreviouslyBound = true;
  16271. this._activateCurrentTexture();
  16272. }
  16273. if (isTextureForRendering && !forTextureDataUpdate) {
  16274. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16275. }
  16276. return wasPreviouslyBound;
  16277. };
  16278. /** @hidden */
  16279. Engine.prototype._bindTexture = function (channel, texture) {
  16280. if (channel < 0) {
  16281. return;
  16282. }
  16283. if (texture) {
  16284. channel = this._getCorrectTextureChannel(channel, texture);
  16285. }
  16286. this._activeChannel = channel;
  16287. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16288. };
  16289. /**
  16290. * Sets a texture to the webGL context from a postprocess
  16291. * @param channel defines the channel to use
  16292. * @param postProcess defines the source postprocess
  16293. */
  16294. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16295. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16296. };
  16297. /**
  16298. * Binds the output of the passed in post process to the texture channel specified
  16299. * @param channel The channel the texture should be bound to
  16300. * @param postProcess The post process which's output should be bound
  16301. */
  16302. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16303. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16304. };
  16305. /**
  16306. * Unbind all textures from the webGL context
  16307. */
  16308. Engine.prototype.unbindAllTextures = function () {
  16309. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16310. this._activeChannel = channel;
  16311. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16312. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16313. if (this.webGLVersion > 1) {
  16314. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16315. }
  16316. }
  16317. };
  16318. /**
  16319. * Sets a texture to the according uniform.
  16320. * @param channel The texture channel
  16321. * @param uniform The uniform to set
  16322. * @param texture The texture to apply
  16323. */
  16324. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16325. if (channel < 0) {
  16326. return;
  16327. }
  16328. if (uniform) {
  16329. this._boundUniforms[channel] = uniform;
  16330. }
  16331. this._setTexture(channel, texture);
  16332. };
  16333. /**
  16334. * Sets a depth stencil texture from a render target to the according uniform.
  16335. * @param channel The texture channel
  16336. * @param uniform The uniform to set
  16337. * @param texture The render target texture containing the depth stencil texture to apply
  16338. */
  16339. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16340. if (channel < 0) {
  16341. return;
  16342. }
  16343. if (uniform) {
  16344. this._boundUniforms[channel] = uniform;
  16345. }
  16346. if (!texture || !texture.depthStencilTexture) {
  16347. this._setTexture(channel, null);
  16348. }
  16349. else {
  16350. this._setTexture(channel, texture, false, true);
  16351. }
  16352. };
  16353. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16354. var uniform = this._boundUniforms[sourceSlot];
  16355. if (uniform._currentState === destination) {
  16356. return;
  16357. }
  16358. this._gl.uniform1i(uniform, destination);
  16359. uniform._currentState = destination;
  16360. };
  16361. Engine.prototype._getTextureWrapMode = function (mode) {
  16362. switch (mode) {
  16363. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16364. return this._gl.REPEAT;
  16365. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16366. return this._gl.CLAMP_TO_EDGE;
  16367. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16368. return this._gl.MIRRORED_REPEAT;
  16369. }
  16370. return this._gl.REPEAT;
  16371. };
  16372. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16373. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16374. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16375. // Not ready?
  16376. if (!texture) {
  16377. if (this._boundTexturesCache[channel] != null) {
  16378. this._activeChannel = channel;
  16379. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16380. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16381. if (this.webGLVersion > 1) {
  16382. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16383. }
  16384. }
  16385. return false;
  16386. }
  16387. // Video
  16388. if (texture.video) {
  16389. this._activeChannel = channel;
  16390. texture.update();
  16391. }
  16392. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16393. texture.delayLoad();
  16394. return false;
  16395. }
  16396. var internalTexture;
  16397. if (depthStencilTexture) {
  16398. internalTexture = texture.depthStencilTexture;
  16399. }
  16400. else if (texture.isReady()) {
  16401. internalTexture = texture.getInternalTexture();
  16402. }
  16403. else if (texture.isCube) {
  16404. internalTexture = this.emptyCubeTexture;
  16405. }
  16406. else if (texture.is3D) {
  16407. internalTexture = this.emptyTexture3D;
  16408. }
  16409. else {
  16410. internalTexture = this.emptyTexture;
  16411. }
  16412. if (!isPartOfTextureArray) {
  16413. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16414. }
  16415. var needToBind = true;
  16416. if (this._boundTexturesCache[channel] === internalTexture) {
  16417. this._moveBoundTextureOnTop(internalTexture);
  16418. if (!isPartOfTextureArray) {
  16419. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16420. }
  16421. needToBind = false;
  16422. }
  16423. this._activeChannel = channel;
  16424. if (internalTexture && internalTexture.is3D) {
  16425. if (needToBind) {
  16426. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16427. }
  16428. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16429. internalTexture._cachedWrapU = texture.wrapU;
  16430. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16431. }
  16432. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16433. internalTexture._cachedWrapV = texture.wrapV;
  16434. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16435. }
  16436. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16437. internalTexture._cachedWrapR = texture.wrapR;
  16438. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16439. }
  16440. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16441. }
  16442. else if (internalTexture && internalTexture.isCube) {
  16443. if (needToBind) {
  16444. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16445. }
  16446. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16447. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16448. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16449. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16450. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16451. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16452. }
  16453. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16454. }
  16455. else {
  16456. if (needToBind) {
  16457. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16458. }
  16459. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16460. internalTexture._cachedWrapU = texture.wrapU;
  16461. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16462. }
  16463. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16464. internalTexture._cachedWrapV = texture.wrapV;
  16465. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16466. }
  16467. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16468. }
  16469. return true;
  16470. };
  16471. /**
  16472. * Sets an array of texture to the webGL context
  16473. * @param channel defines the channel where the texture array must be set
  16474. * @param uniform defines the associated uniform location
  16475. * @param textures defines the array of textures to bind
  16476. */
  16477. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16478. if (channel < 0 || !uniform) {
  16479. return;
  16480. }
  16481. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16482. this._textureUnits = new Int32Array(textures.length);
  16483. }
  16484. for (var i = 0; i < textures.length; i++) {
  16485. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16486. }
  16487. this._gl.uniform1iv(uniform, this._textureUnits);
  16488. for (var index = 0; index < textures.length; index++) {
  16489. this._setTexture(this._textureUnits[index], textures[index], true);
  16490. }
  16491. };
  16492. /** @hidden */
  16493. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16494. var internalTexture = texture.getInternalTexture();
  16495. if (!internalTexture) {
  16496. return;
  16497. }
  16498. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16499. var value = texture.anisotropicFilteringLevel;
  16500. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16501. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16502. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16503. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16504. }
  16505. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16506. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16507. internalTexture._cachedAnisotropicFilteringLevel = value;
  16508. }
  16509. };
  16510. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16511. this._bindTextureDirectly(target, texture, true, true);
  16512. this._gl.texParameterf(target, parameter, value);
  16513. };
  16514. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16515. if (texture) {
  16516. this._bindTextureDirectly(target, texture, true, true);
  16517. }
  16518. this._gl.texParameteri(target, parameter, value);
  16519. };
  16520. /**
  16521. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16522. * @param x defines the x coordinate of the rectangle where pixels must be read
  16523. * @param y defines the y coordinate of the rectangle where pixels must be read
  16524. * @param width defines the width of the rectangle where pixels must be read
  16525. * @param height defines the height of the rectangle where pixels must be read
  16526. * @returns a Uint8Array containing RGBA colors
  16527. */
  16528. Engine.prototype.readPixels = function (x, y, width, height) {
  16529. var data = new Uint8Array(height * width * 4);
  16530. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16531. return data;
  16532. };
  16533. /**
  16534. * Add an externaly attached data from its key.
  16535. * This method call will fail and return false, if such key already exists.
  16536. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16537. * @param key the unique key that identifies the data
  16538. * @param data the data object to associate to the key for this Engine instance
  16539. * @return true if no such key were already present and the data was added successfully, false otherwise
  16540. */
  16541. Engine.prototype.addExternalData = function (key, data) {
  16542. if (!this._externalData) {
  16543. this._externalData = new BABYLON.StringDictionary();
  16544. }
  16545. return this._externalData.add(key, data);
  16546. };
  16547. /**
  16548. * Get an externaly attached data from its key
  16549. * @param key the unique key that identifies the data
  16550. * @return the associated data, if present (can be null), or undefined if not present
  16551. */
  16552. Engine.prototype.getExternalData = function (key) {
  16553. if (!this._externalData) {
  16554. this._externalData = new BABYLON.StringDictionary();
  16555. }
  16556. return this._externalData.get(key);
  16557. };
  16558. /**
  16559. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16560. * @param key the unique key that identifies the data
  16561. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16562. * @return the associated data, can be null if the factory returned null.
  16563. */
  16564. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16565. if (!this._externalData) {
  16566. this._externalData = new BABYLON.StringDictionary();
  16567. }
  16568. return this._externalData.getOrAddWithFactory(key, factory);
  16569. };
  16570. /**
  16571. * Remove an externaly attached data from the Engine instance
  16572. * @param key the unique key that identifies the data
  16573. * @return true if the data was successfully removed, false if it doesn't exist
  16574. */
  16575. Engine.prototype.removeExternalData = function (key) {
  16576. if (!this._externalData) {
  16577. this._externalData = new BABYLON.StringDictionary();
  16578. }
  16579. return this._externalData.remove(key);
  16580. };
  16581. /**
  16582. * Unbind all vertex attributes from the webGL context
  16583. */
  16584. Engine.prototype.unbindAllAttributes = function () {
  16585. if (this._mustWipeVertexAttributes) {
  16586. this._mustWipeVertexAttributes = false;
  16587. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16588. this._gl.disableVertexAttribArray(i);
  16589. this._vertexAttribArraysEnabled[i] = false;
  16590. this._currentBufferPointers[i].active = false;
  16591. }
  16592. return;
  16593. }
  16594. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16595. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16596. continue;
  16597. }
  16598. this._gl.disableVertexAttribArray(i);
  16599. this._vertexAttribArraysEnabled[i] = false;
  16600. this._currentBufferPointers[i].active = false;
  16601. }
  16602. };
  16603. /**
  16604. * 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
  16605. */
  16606. Engine.prototype.releaseEffects = function () {
  16607. for (var name in this._compiledEffects) {
  16608. this._deleteProgram(this._compiledEffects[name]._program);
  16609. }
  16610. this._compiledEffects = {};
  16611. };
  16612. /**
  16613. * Dispose and release all associated resources
  16614. */
  16615. Engine.prototype.dispose = function () {
  16616. this.hideLoadingUI();
  16617. this.stopRenderLoop();
  16618. // Release postProcesses
  16619. while (this.postProcesses.length) {
  16620. this.postProcesses[0].dispose();
  16621. }
  16622. // Empty texture
  16623. if (this._emptyTexture) {
  16624. this._releaseTexture(this._emptyTexture);
  16625. this._emptyTexture = null;
  16626. }
  16627. if (this._emptyCubeTexture) {
  16628. this._releaseTexture(this._emptyCubeTexture);
  16629. this._emptyCubeTexture = null;
  16630. }
  16631. // Rescale PP
  16632. if (this._rescalePostProcess) {
  16633. this._rescalePostProcess.dispose();
  16634. }
  16635. // Release scenes
  16636. while (this.scenes.length) {
  16637. this.scenes[0].dispose();
  16638. }
  16639. // Release audio engine
  16640. if (Engine.audioEngine) {
  16641. Engine.audioEngine.dispose();
  16642. }
  16643. // Release effects
  16644. this.releaseEffects();
  16645. // Unbind
  16646. this.unbindAllAttributes();
  16647. this._boundUniforms = [];
  16648. if (this._dummyFramebuffer) {
  16649. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16650. }
  16651. //WebVR
  16652. this.disableVR();
  16653. // Events
  16654. if (BABYLON.Tools.IsWindowObjectExist()) {
  16655. window.removeEventListener("blur", this._onBlur);
  16656. window.removeEventListener("focus", this._onFocus);
  16657. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16658. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16659. if (this._renderingCanvas) {
  16660. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16661. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16662. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16663. if (!this._doNotHandleContextLost) {
  16664. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16665. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16666. }
  16667. }
  16668. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16669. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16670. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16671. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16672. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16673. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16674. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16675. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16676. if (this._onVrDisplayConnect) {
  16677. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16678. if (this._onVrDisplayDisconnect) {
  16679. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16680. }
  16681. if (this._onVrDisplayPresentChange) {
  16682. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16683. }
  16684. this._onVrDisplayConnect = null;
  16685. this._onVrDisplayDisconnect = null;
  16686. }
  16687. }
  16688. // Remove from Instances
  16689. var index = Engine.Instances.indexOf(this);
  16690. if (index >= 0) {
  16691. Engine.Instances.splice(index, 1);
  16692. }
  16693. this._workingCanvas = null;
  16694. this._workingContext = null;
  16695. this._currentBufferPointers = [];
  16696. this._renderingCanvas = null;
  16697. this._currentProgram = null;
  16698. this._bindedRenderFunction = null;
  16699. this.onResizeObservable.clear();
  16700. this.onCanvasBlurObservable.clear();
  16701. this.onCanvasFocusObservable.clear();
  16702. this.onCanvasPointerOutObservable.clear();
  16703. this.onBeginFrameObservable.clear();
  16704. this.onEndFrameObservable.clear();
  16705. BABYLON.Effect.ResetCache();
  16706. // Abort active requests
  16707. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16708. var request = _a[_i];
  16709. request.abort();
  16710. }
  16711. };
  16712. // Loading screen
  16713. /**
  16714. * Display the loading screen
  16715. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16716. */
  16717. Engine.prototype.displayLoadingUI = function () {
  16718. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16719. return;
  16720. }
  16721. var loadingScreen = this.loadingScreen;
  16722. if (loadingScreen) {
  16723. loadingScreen.displayLoadingUI();
  16724. }
  16725. };
  16726. /**
  16727. * Hide the loading screen
  16728. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16729. */
  16730. Engine.prototype.hideLoadingUI = function () {
  16731. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16732. return;
  16733. }
  16734. var loadingScreen = this.loadingScreen;
  16735. if (loadingScreen) {
  16736. loadingScreen.hideLoadingUI();
  16737. }
  16738. };
  16739. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16740. /**
  16741. * Gets the current loading screen object
  16742. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16743. */
  16744. get: function () {
  16745. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16746. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16747. return this._loadingScreen;
  16748. },
  16749. /**
  16750. * Sets the current loading screen object
  16751. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16752. */
  16753. set: function (loadingScreen) {
  16754. this._loadingScreen = loadingScreen;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16760. /**
  16761. * Sets the current loading screen text
  16762. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16763. */
  16764. set: function (text) {
  16765. this.loadingScreen.loadingUIText = text;
  16766. },
  16767. enumerable: true,
  16768. configurable: true
  16769. });
  16770. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16771. /**
  16772. * Sets the current loading screen background color
  16773. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16774. */
  16775. set: function (color) {
  16776. this.loadingScreen.loadingUIBackgroundColor = color;
  16777. },
  16778. enumerable: true,
  16779. configurable: true
  16780. });
  16781. /**
  16782. * Attach a new callback raised when context lost event is fired
  16783. * @param callback defines the callback to call
  16784. */
  16785. Engine.prototype.attachContextLostEvent = function (callback) {
  16786. if (this._renderingCanvas) {
  16787. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16788. }
  16789. };
  16790. /**
  16791. * Attach a new callback raised when context restored event is fired
  16792. * @param callback defines the callback to call
  16793. */
  16794. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16795. if (this._renderingCanvas) {
  16796. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16797. }
  16798. };
  16799. /**
  16800. * Gets the source code of the vertex shader associated with a specific webGL program
  16801. * @param program defines the program to use
  16802. * @returns a string containing the source code of the vertex shader associated with the program
  16803. */
  16804. Engine.prototype.getVertexShaderSource = function (program) {
  16805. var shaders = this._gl.getAttachedShaders(program);
  16806. if (!shaders) {
  16807. return null;
  16808. }
  16809. return this._gl.getShaderSource(shaders[0]);
  16810. };
  16811. /**
  16812. * Gets the source code of the fragment shader associated with a specific webGL program
  16813. * @param program defines the program to use
  16814. * @returns a string containing the source code of the fragment shader associated with the program
  16815. */
  16816. Engine.prototype.getFragmentShaderSource = function (program) {
  16817. var shaders = this._gl.getAttachedShaders(program);
  16818. if (!shaders) {
  16819. return null;
  16820. }
  16821. return this._gl.getShaderSource(shaders[1]);
  16822. };
  16823. /**
  16824. * Get the current error code of the webGL context
  16825. * @returns the error code
  16826. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16827. */
  16828. Engine.prototype.getError = function () {
  16829. return this._gl.getError();
  16830. };
  16831. // FPS
  16832. /**
  16833. * Gets the current framerate
  16834. * @returns a number representing the framerate
  16835. */
  16836. Engine.prototype.getFps = function () {
  16837. return this._fps;
  16838. };
  16839. /**
  16840. * Gets the time spent between current and previous frame
  16841. * @returns a number representing the delta time in ms
  16842. */
  16843. Engine.prototype.getDeltaTime = function () {
  16844. return this._deltaTime;
  16845. };
  16846. Engine.prototype._measureFps = function () {
  16847. this._performanceMonitor.sampleFrame();
  16848. this._fps = this._performanceMonitor.averageFPS;
  16849. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16850. };
  16851. /** @hidden */
  16852. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16853. if (faceIndex === void 0) { faceIndex = -1; }
  16854. if (level === void 0) { level = 0; }
  16855. var gl = this._gl;
  16856. if (!this._dummyFramebuffer) {
  16857. var dummy = gl.createFramebuffer();
  16858. if (!dummy) {
  16859. throw new Error("Unable to create dummy framebuffer");
  16860. }
  16861. this._dummyFramebuffer = dummy;
  16862. }
  16863. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16864. if (faceIndex > -1) {
  16865. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16866. }
  16867. else {
  16868. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16869. }
  16870. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16871. var buffer;
  16872. switch (readType) {
  16873. case gl.UNSIGNED_BYTE:
  16874. buffer = new Uint8Array(4 * width * height);
  16875. readType = gl.UNSIGNED_BYTE;
  16876. break;
  16877. default:
  16878. buffer = new Float32Array(4 * width * height);
  16879. readType = gl.FLOAT;
  16880. break;
  16881. }
  16882. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16883. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16884. return buffer;
  16885. };
  16886. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16887. if (this._webGLVersion > 1) {
  16888. return this._caps.colorBufferFloat;
  16889. }
  16890. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16891. };
  16892. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16893. if (this._webGLVersion > 1) {
  16894. return this._caps.colorBufferFloat;
  16895. }
  16896. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16897. };
  16898. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16899. Engine.prototype._canRenderToFramebuffer = function (type) {
  16900. var gl = this._gl;
  16901. //clear existing errors
  16902. while (gl.getError() !== gl.NO_ERROR) { }
  16903. var successful = true;
  16904. var texture = gl.createTexture();
  16905. gl.bindTexture(gl.TEXTURE_2D, texture);
  16906. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16909. var fb = gl.createFramebuffer();
  16910. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16911. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16912. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16913. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16914. successful = successful && (gl.getError() === gl.NO_ERROR);
  16915. //try render by clearing frame buffer's color buffer
  16916. if (successful) {
  16917. gl.clear(gl.COLOR_BUFFER_BIT);
  16918. successful = successful && (gl.getError() === gl.NO_ERROR);
  16919. }
  16920. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16921. if (successful) {
  16922. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16923. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16924. var readFormat = gl.RGBA;
  16925. var readType = gl.UNSIGNED_BYTE;
  16926. var buffer = new Uint8Array(4);
  16927. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16928. successful = successful && (gl.getError() === gl.NO_ERROR);
  16929. }
  16930. //clean up
  16931. gl.deleteTexture(texture);
  16932. gl.deleteFramebuffer(fb);
  16933. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16934. //clear accumulated errors
  16935. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16936. return successful;
  16937. };
  16938. /** @hidden */
  16939. Engine.prototype._getWebGLTextureType = function (type) {
  16940. if (this._webGLVersion === 1) {
  16941. switch (type) {
  16942. case Engine.TEXTURETYPE_FLOAT:
  16943. return this._gl.FLOAT;
  16944. case Engine.TEXTURETYPE_HALF_FLOAT:
  16945. return this._gl.HALF_FLOAT_OES;
  16946. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16947. return this._gl.UNSIGNED_BYTE;
  16948. }
  16949. return this._gl.UNSIGNED_BYTE;
  16950. }
  16951. switch (type) {
  16952. case Engine.TEXTURETYPE_BYTE:
  16953. return this._gl.BYTE;
  16954. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16955. return this._gl.UNSIGNED_BYTE;
  16956. case Engine.TEXTURETYPE_SHORT:
  16957. return this._gl.SHORT;
  16958. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16959. return this._gl.UNSIGNED_SHORT;
  16960. case Engine.TEXTURETYPE_INT:
  16961. return this._gl.INT;
  16962. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16963. return this._gl.UNSIGNED_INT;
  16964. case Engine.TEXTURETYPE_FLOAT:
  16965. return this._gl.FLOAT;
  16966. case Engine.TEXTURETYPE_HALF_FLOAT:
  16967. return this._gl.HALF_FLOAT;
  16968. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16969. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16970. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16971. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16972. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16973. return this._gl.UNSIGNED_SHORT_5_6_5;
  16974. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16975. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16976. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16977. return this._gl.UNSIGNED_INT_24_8;
  16978. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16979. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16980. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16981. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16982. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16983. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16984. }
  16985. return this._gl.UNSIGNED_BYTE;
  16986. };
  16987. ;
  16988. Engine.prototype._getInternalFormat = function (format) {
  16989. var internalFormat = this._gl.RGBA;
  16990. switch (format) {
  16991. case Engine.TEXTUREFORMAT_ALPHA:
  16992. internalFormat = this._gl.ALPHA;
  16993. break;
  16994. case Engine.TEXTUREFORMAT_LUMINANCE:
  16995. internalFormat = this._gl.LUMINANCE;
  16996. break;
  16997. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16998. internalFormat = this._gl.LUMINANCE_ALPHA;
  16999. break;
  17000. case Engine.TEXTUREFORMAT_RED:
  17001. internalFormat = this._gl.RED;
  17002. break;
  17003. case Engine.TEXTUREFORMAT_RG:
  17004. internalFormat = this._gl.RG;
  17005. break;
  17006. case Engine.TEXTUREFORMAT_RGB:
  17007. internalFormat = this._gl.RGB;
  17008. break;
  17009. case Engine.TEXTUREFORMAT_RGBA:
  17010. internalFormat = this._gl.RGBA;
  17011. break;
  17012. }
  17013. if (this._webGLVersion > 1) {
  17014. switch (format) {
  17015. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17016. internalFormat = this._gl.RED_INTEGER;
  17017. break;
  17018. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17019. internalFormat = this._gl.RG_INTEGER;
  17020. break;
  17021. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17022. internalFormat = this._gl.RGB_INTEGER;
  17023. break;
  17024. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17025. internalFormat = this._gl.RGBA_INTEGER;
  17026. break;
  17027. }
  17028. }
  17029. return internalFormat;
  17030. };
  17031. /** @hidden */
  17032. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17033. if (this._webGLVersion === 1) {
  17034. if (format !== undefined) {
  17035. switch (format) {
  17036. case Engine.TEXTUREFORMAT_ALPHA:
  17037. return this._gl.ALPHA;
  17038. case Engine.TEXTUREFORMAT_LUMINANCE:
  17039. return this._gl.LUMINANCE;
  17040. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17041. return this._gl.LUMINANCE_ALPHA;
  17042. }
  17043. }
  17044. return this._gl.RGBA;
  17045. }
  17046. switch (type) {
  17047. case Engine.TEXTURETYPE_BYTE:
  17048. switch (format) {
  17049. case Engine.TEXTUREFORMAT_RED:
  17050. return this._gl.R8_SNORM;
  17051. case Engine.TEXTUREFORMAT_RG:
  17052. return this._gl.RG8_SNORM;
  17053. case Engine.TEXTUREFORMAT_RGB:
  17054. return this._gl.RGB8_SNORM;
  17055. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17056. return this._gl.R8I;
  17057. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17058. return this._gl.RG8I;
  17059. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17060. return this._gl.RGB8I;
  17061. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17062. return this._gl.RGBA8I;
  17063. default:
  17064. return this._gl.RGBA8_SNORM;
  17065. }
  17066. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17067. switch (format) {
  17068. case Engine.TEXTUREFORMAT_RED:
  17069. return this._gl.R8;
  17070. case Engine.TEXTUREFORMAT_RG:
  17071. return this._gl.RG8;
  17072. case Engine.TEXTUREFORMAT_RGB:
  17073. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17074. case Engine.TEXTUREFORMAT_RGBA:
  17075. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17076. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17077. return this._gl.R8UI;
  17078. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17079. return this._gl.RG8UI;
  17080. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17081. return this._gl.RGB8UI;
  17082. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17083. return this._gl.RGBA8UI;
  17084. default:
  17085. return this._gl.RGBA8;
  17086. }
  17087. case Engine.TEXTURETYPE_SHORT:
  17088. switch (format) {
  17089. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17090. return this._gl.R16I;
  17091. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17092. return this._gl.RG16I;
  17093. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17094. return this._gl.RGB16I;
  17095. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17096. return this._gl.RGBA16I;
  17097. default:
  17098. return this._gl.RGBA16I;
  17099. }
  17100. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17101. switch (format) {
  17102. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17103. return this._gl.R16UI;
  17104. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17105. return this._gl.RG16UI;
  17106. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17107. return this._gl.RGB16UI;
  17108. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17109. return this._gl.RGBA16UI;
  17110. default:
  17111. return this._gl.RGBA16UI;
  17112. }
  17113. case Engine.TEXTURETYPE_INT:
  17114. switch (format) {
  17115. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17116. return this._gl.R32I;
  17117. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17118. return this._gl.RG32I;
  17119. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17120. return this._gl.RGB32I;
  17121. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17122. return this._gl.RGBA32I;
  17123. default:
  17124. return this._gl.RGBA32I;
  17125. }
  17126. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17127. switch (format) {
  17128. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17129. return this._gl.R32UI;
  17130. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17131. return this._gl.RG32UI;
  17132. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17133. return this._gl.RGB32UI;
  17134. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17135. return this._gl.RGBA32UI;
  17136. default:
  17137. return this._gl.RGBA32UI;
  17138. }
  17139. case Engine.TEXTURETYPE_FLOAT:
  17140. switch (format) {
  17141. case Engine.TEXTUREFORMAT_RED:
  17142. return this._gl.R32F; // By default. Other possibility is R16F.
  17143. case Engine.TEXTUREFORMAT_RG:
  17144. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17145. case Engine.TEXTUREFORMAT_RGB:
  17146. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17147. case Engine.TEXTUREFORMAT_RGBA:
  17148. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17149. default:
  17150. return this._gl.RGBA32F;
  17151. }
  17152. case Engine.TEXTURETYPE_HALF_FLOAT:
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_RED:
  17155. return this._gl.R16F;
  17156. case Engine.TEXTUREFORMAT_RG:
  17157. return this._gl.RG16F;
  17158. case Engine.TEXTUREFORMAT_RGB:
  17159. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17160. case Engine.TEXTUREFORMAT_RGBA:
  17161. return this._gl.RGBA16F;
  17162. default:
  17163. return this._gl.RGBA16F;
  17164. }
  17165. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17166. return this._gl.RGB565;
  17167. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17168. return this._gl.R11F_G11F_B10F;
  17169. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17170. return this._gl.RGB9_E5;
  17171. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17172. return this._gl.RGBA4;
  17173. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17174. return this._gl.RGB5_A1;
  17175. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17176. switch (format) {
  17177. case Engine.TEXTUREFORMAT_RGBA:
  17178. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17179. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17180. return this._gl.RGB10_A2UI;
  17181. default:
  17182. return this._gl.RGB10_A2;
  17183. }
  17184. }
  17185. return this._gl.RGBA8;
  17186. };
  17187. ;
  17188. /** @hidden */
  17189. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17190. if (type === Engine.TEXTURETYPE_FLOAT) {
  17191. return this._gl.RGBA32F;
  17192. }
  17193. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17194. return this._gl.RGBA16F;
  17195. }
  17196. return this._gl.RGBA8;
  17197. };
  17198. ;
  17199. /** @hidden */
  17200. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17201. var _this = this;
  17202. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17203. this._activeRequests.push(request);
  17204. request.onCompleteObservable.add(function (request) {
  17205. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17206. });
  17207. return request;
  17208. };
  17209. /** @hidden */
  17210. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17211. var _this = this;
  17212. return new Promise(function (resolve, reject) {
  17213. _this._loadFile(url, function (data) {
  17214. resolve(data);
  17215. }, undefined, database, useArrayBuffer, function (request, exception) {
  17216. reject(exception);
  17217. });
  17218. });
  17219. };
  17220. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17221. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17222. var onload = function (data) {
  17223. loadedFiles[index] = data;
  17224. loadedFiles._internalCount++;
  17225. if (loadedFiles._internalCount === 6) {
  17226. onfinish(loadedFiles);
  17227. }
  17228. };
  17229. var onerror = function (request, exception) {
  17230. if (onErrorCallBack && request) {
  17231. onErrorCallBack(request.status + " " + request.statusText, exception);
  17232. }
  17233. };
  17234. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17235. };
  17236. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17237. if (onError === void 0) { onError = null; }
  17238. var loadedFiles = [];
  17239. loadedFiles._internalCount = 0;
  17240. for (var index = 0; index < 6; index++) {
  17241. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17242. }
  17243. };
  17244. // Statics
  17245. /**
  17246. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17247. * @returns true if the engine can be created
  17248. * @ignorenaming
  17249. */
  17250. Engine.isSupported = function () {
  17251. try {
  17252. var tempcanvas = document.createElement("canvas");
  17253. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17254. return gl != null && !!window.WebGLRenderingContext;
  17255. }
  17256. catch (e) {
  17257. return false;
  17258. }
  17259. };
  17260. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17261. Engine.ExceptionList = [
  17262. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17263. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17264. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17265. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17266. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17267. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17268. ];
  17269. /** Gets the list of created engines */
  17270. Engine.Instances = new Array();
  17271. /**
  17272. * Hidden
  17273. */
  17274. Engine._TextureLoaders = [];
  17275. // Const statics
  17276. /** Defines that alpha blending is disabled */
  17277. Engine.ALPHA_DISABLE = 0;
  17278. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17279. Engine.ALPHA_ADD = 1;
  17280. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17281. Engine.ALPHA_COMBINE = 2;
  17282. /** Defines that alpha blending to DEST - SRC * DEST */
  17283. Engine.ALPHA_SUBTRACT = 3;
  17284. /** Defines that alpha blending to SRC * DEST */
  17285. Engine.ALPHA_MULTIPLY = 4;
  17286. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17287. Engine.ALPHA_MAXIMIZED = 5;
  17288. /** Defines that alpha blending to SRC + DEST */
  17289. Engine.ALPHA_ONEONE = 6;
  17290. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17291. Engine.ALPHA_PREMULTIPLIED = 7;
  17292. /**
  17293. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17294. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17295. */
  17296. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17297. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17298. Engine.ALPHA_INTERPOLATE = 9;
  17299. /**
  17300. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17301. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17302. */
  17303. Engine.ALPHA_SCREENMODE = 10;
  17304. /** Defines that the ressource is not delayed*/
  17305. Engine.DELAYLOADSTATE_NONE = 0;
  17306. /** Defines that the ressource was successfully delay loaded */
  17307. Engine.DELAYLOADSTATE_LOADED = 1;
  17308. /** Defines that the ressource is currently delay loading */
  17309. Engine.DELAYLOADSTATE_LOADING = 2;
  17310. /** Defines that the ressource is delayed and has not started loading */
  17311. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17312. // Depht or Stencil test Constants.
  17313. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17314. Engine.NEVER = 0x0200;
  17315. /** 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 */
  17316. Engine.ALWAYS = 0x0207;
  17317. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17318. Engine.LESS = 0x0201;
  17319. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17320. Engine.EQUAL = 0x0202;
  17321. /** 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 */
  17322. Engine.LEQUAL = 0x0203;
  17323. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17324. Engine.GREATER = 0x0204;
  17325. /** 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 */
  17326. Engine.GEQUAL = 0x0206;
  17327. /** 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 */
  17328. Engine.NOTEQUAL = 0x0205;
  17329. // Stencil Actions Constants.
  17330. /** Passed to stencilOperation to specify that stencil value must be kept */
  17331. Engine.KEEP = 0x1E00;
  17332. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17333. Engine.REPLACE = 0x1E01;
  17334. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17335. Engine.INCR = 0x1E02;
  17336. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17337. Engine.DECR = 0x1E03;
  17338. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17339. Engine.INVERT = 0x150A;
  17340. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17341. Engine.INCR_WRAP = 0x8507;
  17342. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17343. Engine.DECR_WRAP = 0x8508;
  17344. /** Texture is not repeating outside of 0..1 UVs */
  17345. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17346. /** Texture is repeating outside of 0..1 UVs */
  17347. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17348. /** Texture is repeating and mirrored */
  17349. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17350. /** ALPHA */
  17351. Engine.TEXTUREFORMAT_ALPHA = 0;
  17352. /** LUMINANCE */
  17353. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17354. /** LUMINANCE_ALPHA */
  17355. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17356. /** RGB */
  17357. Engine.TEXTUREFORMAT_RGB = 4;
  17358. /** RGBA */
  17359. Engine.TEXTUREFORMAT_RGBA = 5;
  17360. /** RED */
  17361. Engine.TEXTUREFORMAT_RED = 6;
  17362. /** RED (2nd reference) */
  17363. Engine.TEXTUREFORMAT_R = 6;
  17364. /** RG */
  17365. Engine.TEXTUREFORMAT_RG = 7;
  17366. /** RED_INTEGER */
  17367. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17368. /** RED_INTEGER (2nd reference) */
  17369. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17370. /** RG_INTEGER */
  17371. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17372. /** RGB_INTEGER */
  17373. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17374. /** RGBA_INTEGER */
  17375. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17376. /** UNSIGNED_BYTE */
  17377. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17378. /** UNSIGNED_BYTE (2nd reference) */
  17379. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17380. /** FLOAT */
  17381. Engine.TEXTURETYPE_FLOAT = 1;
  17382. /** HALF_FLOAT */
  17383. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17384. /** BYTE */
  17385. Engine.TEXTURETYPE_BYTE = 3;
  17386. /** SHORT */
  17387. Engine.TEXTURETYPE_SHORT = 4;
  17388. /** UNSIGNED_SHORT */
  17389. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17390. /** INT */
  17391. Engine.TEXTURETYPE_INT = 6;
  17392. /** UNSIGNED_INT */
  17393. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17394. /** UNSIGNED_SHORT_4_4_4_4 */
  17395. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17396. /** UNSIGNED_SHORT_5_5_5_1 */
  17397. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17398. /** UNSIGNED_SHORT_5_6_5 */
  17399. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17400. /** UNSIGNED_INT_2_10_10_10_REV */
  17401. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17402. /** UNSIGNED_INT_24_8 */
  17403. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17404. /** UNSIGNED_INT_10F_11F_11F_REV */
  17405. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17406. /** UNSIGNED_INT_5_9_9_9_REV */
  17407. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17408. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17409. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17410. /** nearest is mag = nearest and min = nearest and mip = linear */
  17411. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17412. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17413. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17414. /** Trilinear is mag = linear and min = linear and mip = linear */
  17415. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17416. /** nearest is mag = nearest and min = nearest and mip = linear */
  17417. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17418. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17419. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17420. /** Trilinear is mag = linear and min = linear and mip = linear */
  17421. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17422. /** mag = nearest and min = nearest and mip = nearest */
  17423. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17424. /** mag = nearest and min = linear and mip = nearest */
  17425. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17426. /** mag = nearest and min = linear and mip = linear */
  17427. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17428. /** mag = nearest and min = linear and mip = none */
  17429. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17430. /** mag = nearest and min = nearest and mip = none */
  17431. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17432. /** mag = linear and min = nearest and mip = nearest */
  17433. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17434. /** mag = linear and min = nearest and mip = linear */
  17435. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17436. /** mag = linear and min = linear and mip = none */
  17437. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17438. /** mag = linear and min = nearest and mip = none */
  17439. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17440. /** Explicit coordinates mode */
  17441. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17442. /** Spherical coordinates mode */
  17443. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17444. /** Planar coordinates mode */
  17445. Engine.TEXTURE_PLANAR_MODE = 2;
  17446. /** Cubic coordinates mode */
  17447. Engine.TEXTURE_CUBIC_MODE = 3;
  17448. /** Projection coordinates mode */
  17449. Engine.TEXTURE_PROJECTION_MODE = 4;
  17450. /** Skybox coordinates mode */
  17451. Engine.TEXTURE_SKYBOX_MODE = 5;
  17452. /** Inverse Cubic coordinates mode */
  17453. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17454. /** Equirectangular coordinates mode */
  17455. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17456. /** Equirectangular Fixed coordinates mode */
  17457. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17458. /** Equirectangular Fixed Mirrored coordinates mode */
  17459. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17460. // Texture rescaling mode
  17461. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17462. Engine.SCALEMODE_FLOOR = 1;
  17463. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17464. Engine.SCALEMODE_NEAREST = 2;
  17465. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17466. Engine.SCALEMODE_CEILING = 3;
  17467. // Updatable statics so stick with vars here
  17468. /**
  17469. * Gets or sets the epsilon value used by collision engine
  17470. */
  17471. Engine.CollisionsEpsilon = 0.001;
  17472. /**
  17473. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17474. */
  17475. Engine.CodeRepository = "src/";
  17476. /**
  17477. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17478. */
  17479. Engine.ShadersRepository = "src/Shaders/";
  17480. return Engine;
  17481. }());
  17482. BABYLON.Engine = Engine;
  17483. })(BABYLON || (BABYLON = {}));
  17484. //# sourceMappingURL=babylon.engine.js.map
  17485. var BABYLON;
  17486. (function (BABYLON) {
  17487. /**
  17488. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17489. */
  17490. var Node = /** @class */ (function () {
  17491. /**
  17492. * Creates a new Node
  17493. * @param {string} name - the name and id to be given to this node
  17494. * @param {BABYLON.Scene} the scene this node will be added to
  17495. */
  17496. function Node(name, scene) {
  17497. if (scene === void 0) { scene = null; }
  17498. /**
  17499. * Gets or sets a string used to store user defined state for the node
  17500. */
  17501. this.state = "";
  17502. /**
  17503. * Gets or sets an object used to store user defined information for the node
  17504. */
  17505. this.metadata = null;
  17506. /**
  17507. * Gets or sets a boolean used to define if the node must be serialized
  17508. */
  17509. this.doNotSerialize = false;
  17510. /** @hidden */
  17511. this._isDisposed = false;
  17512. /**
  17513. * Gets a list of Animations associated with the node
  17514. */
  17515. this.animations = new Array();
  17516. this._ranges = {};
  17517. this._isEnabled = true;
  17518. this._isReady = true;
  17519. /** @hidden */
  17520. this._currentRenderId = -1;
  17521. this._parentRenderId = -1;
  17522. this._childRenderId = -1;
  17523. this._animationPropertiesOverride = null;
  17524. /**
  17525. * An event triggered when the mesh is disposed
  17526. */
  17527. this.onDisposeObservable = new BABYLON.Observable();
  17528. // Behaviors
  17529. this._behaviors = new Array();
  17530. this.name = name;
  17531. this.id = name;
  17532. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17533. this.uniqueId = this._scene.getUniqueId();
  17534. this._initCache();
  17535. }
  17536. /**
  17537. * Add a new node constructor
  17538. * @param type defines the type name of the node to construct
  17539. * @param constructorFunc defines the constructor function
  17540. */
  17541. Node.AddNodeConstructor = function (type, constructorFunc) {
  17542. this._NodeConstructors[type] = constructorFunc;
  17543. };
  17544. /**
  17545. * Returns a node constructor based on type name
  17546. * @param type defines the type name
  17547. * @param name defines the new node name
  17548. * @param scene defines the hosting scene
  17549. * @param options defines optional options to transmit to constructors
  17550. * @returns the new constructor or null
  17551. */
  17552. Node.Construct = function (type, name, scene, options) {
  17553. var constructorFunc = this._NodeConstructors[type];
  17554. if (!constructorFunc) {
  17555. return null;
  17556. }
  17557. return constructorFunc(name, scene, options);
  17558. };
  17559. /**
  17560. * Gets a boolean indicating if the node has been disposed
  17561. * @returns true if the node was disposed
  17562. */
  17563. Node.prototype.isDisposed = function () {
  17564. return this._isDisposed;
  17565. };
  17566. Object.defineProperty(Node.prototype, "parent", {
  17567. get: function () {
  17568. return this._parentNode;
  17569. },
  17570. /**
  17571. * Gets or sets the parent of the node
  17572. */
  17573. set: function (parent) {
  17574. if (this._parentNode === parent) {
  17575. return;
  17576. }
  17577. // Remove self from list of children of parent
  17578. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17579. var index = this._parentNode._children.indexOf(this);
  17580. if (index !== -1) {
  17581. this._parentNode._children.splice(index, 1);
  17582. }
  17583. }
  17584. // Store new parent
  17585. this._parentNode = parent;
  17586. // Add as child to new parent
  17587. if (this._parentNode) {
  17588. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17589. this._parentNode._children = new Array();
  17590. }
  17591. this._parentNode._children.push(this);
  17592. }
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17598. /**
  17599. * Gets or sets the animation properties override
  17600. */
  17601. get: function () {
  17602. if (!this._animationPropertiesOverride) {
  17603. return this._scene.animationPropertiesOverride;
  17604. }
  17605. return this._animationPropertiesOverride;
  17606. },
  17607. set: function (value) {
  17608. this._animationPropertiesOverride = value;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. /**
  17614. * Gets a string idenfifying the name of the class
  17615. * @returns "Node" string
  17616. */
  17617. Node.prototype.getClassName = function () {
  17618. return "Node";
  17619. };
  17620. Object.defineProperty(Node.prototype, "onDispose", {
  17621. /**
  17622. * Sets a callback that will be raised when the node will be disposed
  17623. */
  17624. set: function (callback) {
  17625. if (this._onDisposeObserver) {
  17626. this.onDisposeObservable.remove(this._onDisposeObserver);
  17627. }
  17628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Gets the scene of the node
  17635. * @returns a {BABYLON.Scene}
  17636. */
  17637. Node.prototype.getScene = function () {
  17638. return this._scene;
  17639. };
  17640. /**
  17641. * Gets the engine of the node
  17642. * @returns a {BABYLON.Engine}
  17643. */
  17644. Node.prototype.getEngine = function () {
  17645. return this._scene.getEngine();
  17646. };
  17647. /**
  17648. * Attach a behavior to the node
  17649. * @see http://doc.babylonjs.com/features/behaviour
  17650. * @param behavior defines the behavior to attach
  17651. * @returns the current Node
  17652. */
  17653. Node.prototype.addBehavior = function (behavior) {
  17654. var _this = this;
  17655. var index = this._behaviors.indexOf(behavior);
  17656. if (index !== -1) {
  17657. return this;
  17658. }
  17659. behavior.init();
  17660. if (this._scene.isLoading) {
  17661. // We defer the attach when the scene will be loaded
  17662. this._scene.onDataLoadedObservable.addOnce(function () {
  17663. behavior.attach(_this);
  17664. });
  17665. }
  17666. else {
  17667. behavior.attach(this);
  17668. }
  17669. this._behaviors.push(behavior);
  17670. return this;
  17671. };
  17672. /**
  17673. * Remove an attached behavior
  17674. * @see http://doc.babylonjs.com/features/behaviour
  17675. * @param behavior defines the behavior to attach
  17676. * @returns the current Node
  17677. */
  17678. Node.prototype.removeBehavior = function (behavior) {
  17679. var index = this._behaviors.indexOf(behavior);
  17680. if (index === -1) {
  17681. return this;
  17682. }
  17683. this._behaviors[index].detach();
  17684. this._behaviors.splice(index, 1);
  17685. return this;
  17686. };
  17687. Object.defineProperty(Node.prototype, "behaviors", {
  17688. /**
  17689. * Gets the list of attached behaviors
  17690. * @see http://doc.babylonjs.com/features/behaviour
  17691. */
  17692. get: function () {
  17693. return this._behaviors;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. /**
  17699. * Gets an attached behavior by name
  17700. * @param name defines the name of the behavior to look for
  17701. * @see http://doc.babylonjs.com/features/behaviour
  17702. * @returns null if behavior was not found else the requested behavior
  17703. */
  17704. Node.prototype.getBehaviorByName = function (name) {
  17705. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17706. var behavior = _a[_i];
  17707. if (behavior.name === name) {
  17708. return behavior;
  17709. }
  17710. }
  17711. return null;
  17712. };
  17713. /**
  17714. * Returns the world matrix of the node
  17715. * @returns a matrix containing the node's world matrix
  17716. */
  17717. Node.prototype.getWorldMatrix = function () {
  17718. return BABYLON.Matrix.Identity();
  17719. };
  17720. /** @hidden */
  17721. Node.prototype._getWorldMatrixDeterminant = function () {
  17722. return 1;
  17723. };
  17724. // override it in derived class if you add new variables to the cache
  17725. // and call the parent class method
  17726. /** @hidden */
  17727. Node.prototype._initCache = function () {
  17728. this._cache = {};
  17729. this._cache.parent = undefined;
  17730. };
  17731. /** @hidden */
  17732. Node.prototype.updateCache = function (force) {
  17733. if (!force && this.isSynchronized())
  17734. return;
  17735. this._cache.parent = this.parent;
  17736. this._updateCache();
  17737. };
  17738. // override it in derived class if you add new variables to the cache
  17739. // and call the parent class method if !ignoreParentClass
  17740. /** @hidden */
  17741. Node.prototype._updateCache = function (ignoreParentClass) {
  17742. };
  17743. // override it in derived class if you add new variables to the cache
  17744. /** @hidden */
  17745. Node.prototype._isSynchronized = function () {
  17746. return true;
  17747. };
  17748. /** @hidden */
  17749. Node.prototype._markSyncedWithParent = function () {
  17750. if (this.parent) {
  17751. this._parentRenderId = this.parent._childRenderId;
  17752. }
  17753. };
  17754. /** @hidden */
  17755. Node.prototype.isSynchronizedWithParent = function () {
  17756. if (!this.parent) {
  17757. return true;
  17758. }
  17759. if (this._parentRenderId !== this.parent._childRenderId) {
  17760. return false;
  17761. }
  17762. return this.parent.isSynchronized();
  17763. };
  17764. /** @hidden */
  17765. Node.prototype.isSynchronized = function (updateCache) {
  17766. var check = this.hasNewParent();
  17767. check = check || !this.isSynchronizedWithParent();
  17768. check = check || !this._isSynchronized();
  17769. if (updateCache)
  17770. this.updateCache(true);
  17771. return !check;
  17772. };
  17773. /** @hidden */
  17774. Node.prototype.hasNewParent = function (update) {
  17775. if (this._cache.parent === this.parent)
  17776. return false;
  17777. if (update)
  17778. this._cache.parent = this.parent;
  17779. return true;
  17780. };
  17781. /**
  17782. * Is this node ready to be used/rendered
  17783. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17784. * @return true if the node is ready
  17785. */
  17786. Node.prototype.isReady = function (completeCheck) {
  17787. if (completeCheck === void 0) { completeCheck = false; }
  17788. return this._isReady;
  17789. };
  17790. /**
  17791. * Is this node enabled?
  17792. * 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
  17793. * @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
  17794. * @return whether this node (and its parent) is enabled
  17795. */
  17796. Node.prototype.isEnabled = function (checkAncestors) {
  17797. if (checkAncestors === void 0) { checkAncestors = true; }
  17798. if (checkAncestors === false) {
  17799. return this._isEnabled;
  17800. }
  17801. if (this._isEnabled === false) {
  17802. return false;
  17803. }
  17804. if (this.parent !== undefined && this.parent !== null) {
  17805. return this.parent.isEnabled(checkAncestors);
  17806. }
  17807. return true;
  17808. };
  17809. /**
  17810. * Set the enabled state of this node
  17811. * @param value defines the new enabled state
  17812. */
  17813. Node.prototype.setEnabled = function (value) {
  17814. this._isEnabled = value;
  17815. };
  17816. /**
  17817. * Is this node a descendant of the given node?
  17818. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17819. * @param ancestor defines the parent node to inspect
  17820. * @returns a boolean indicating if this node is a descendant of the given node
  17821. */
  17822. Node.prototype.isDescendantOf = function (ancestor) {
  17823. if (this.parent) {
  17824. if (this.parent === ancestor) {
  17825. return true;
  17826. }
  17827. return this.parent.isDescendantOf(ancestor);
  17828. }
  17829. return false;
  17830. };
  17831. /** @hidden */
  17832. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17833. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17834. if (!this._children) {
  17835. return;
  17836. }
  17837. for (var index = 0; index < this._children.length; index++) {
  17838. var item = this._children[index];
  17839. if (!predicate || predicate(item)) {
  17840. results.push(item);
  17841. }
  17842. if (!directDescendantsOnly) {
  17843. item._getDescendants(results, false, predicate);
  17844. }
  17845. }
  17846. };
  17847. /**
  17848. * Will return all nodes that have this node as ascendant
  17849. * @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
  17850. * @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
  17851. * @return all children nodes of all types
  17852. */
  17853. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17854. var results = new Array();
  17855. this._getDescendants(results, directDescendantsOnly, predicate);
  17856. return results;
  17857. };
  17858. /**
  17859. * Get all child-meshes of this node
  17860. * @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
  17861. * @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
  17862. * @returns an array of {BABYLON.AbstractMesh}
  17863. */
  17864. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17865. var results = [];
  17866. this._getDescendants(results, directDescendantsOnly, function (node) {
  17867. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17868. });
  17869. return results;
  17870. };
  17871. /**
  17872. * Get all child-transformNodes of this node
  17873. * @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
  17874. * @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
  17875. * @returns an array of {BABYLON.TransformNode}
  17876. */
  17877. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17878. var results = [];
  17879. this._getDescendants(results, directDescendantsOnly, function (node) {
  17880. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17881. });
  17882. return results;
  17883. };
  17884. /**
  17885. * Get all direct children of this node
  17886. * @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
  17887. * @returns an array of {BABYLON.Node}
  17888. */
  17889. Node.prototype.getChildren = function (predicate) {
  17890. return this.getDescendants(true, predicate);
  17891. };
  17892. /** @hidden */
  17893. Node.prototype._setReady = function (state) {
  17894. if (state === this._isReady) {
  17895. return;
  17896. }
  17897. if (!state) {
  17898. this._isReady = false;
  17899. return;
  17900. }
  17901. if (this.onReady) {
  17902. this.onReady(this);
  17903. }
  17904. this._isReady = true;
  17905. };
  17906. /**
  17907. * Get an animation by name
  17908. * @param name defines the name of the animation to look for
  17909. * @returns null if not found else the requested animation
  17910. */
  17911. Node.prototype.getAnimationByName = function (name) {
  17912. for (var i = 0; i < this.animations.length; i++) {
  17913. var animation = this.animations[i];
  17914. if (animation.name === name) {
  17915. return animation;
  17916. }
  17917. }
  17918. return null;
  17919. };
  17920. /**
  17921. * Creates an animation range for this node
  17922. * @param name defines the name of the range
  17923. * @param from defines the starting key
  17924. * @param to defines the end key
  17925. */
  17926. Node.prototype.createAnimationRange = function (name, from, to) {
  17927. // check name not already in use
  17928. if (!this._ranges[name]) {
  17929. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17930. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17931. if (this.animations[i]) {
  17932. this.animations[i].createRange(name, from, to);
  17933. }
  17934. }
  17935. }
  17936. };
  17937. /**
  17938. * Delete a specific animation range
  17939. * @param name defines the name of the range to delete
  17940. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17941. */
  17942. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17943. if (deleteFrames === void 0) { deleteFrames = true; }
  17944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17945. if (this.animations[i]) {
  17946. this.animations[i].deleteRange(name, deleteFrames);
  17947. }
  17948. }
  17949. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17950. };
  17951. /**
  17952. * Get an animation range by name
  17953. * @param name defines the name of the animation range to look for
  17954. * @returns null if not found else the requested animation range
  17955. */
  17956. Node.prototype.getAnimationRange = function (name) {
  17957. return this._ranges[name];
  17958. };
  17959. /**
  17960. * Will start the animation sequence
  17961. * @param name defines the range frames for animation sequence
  17962. * @param loop defines if the animation should loop (false by default)
  17963. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17964. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17965. * @returns the object created for this animation. If range does not exist, it will return null
  17966. */
  17967. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17968. var range = this.getAnimationRange(name);
  17969. if (!range) {
  17970. return null;
  17971. }
  17972. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17973. };
  17974. /**
  17975. * Serialize animation ranges into a JSON compatible object
  17976. * @returns serialization object
  17977. */
  17978. Node.prototype.serializeAnimationRanges = function () {
  17979. var serializationRanges = [];
  17980. for (var name in this._ranges) {
  17981. var localRange = this._ranges[name];
  17982. if (!localRange) {
  17983. continue;
  17984. }
  17985. var range = {};
  17986. range.name = name;
  17987. range.from = localRange.from;
  17988. range.to = localRange.to;
  17989. serializationRanges.push(range);
  17990. }
  17991. return serializationRanges;
  17992. };
  17993. /**
  17994. * Computes the world matrix of the node
  17995. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17996. * @returns the world matrix
  17997. */
  17998. Node.prototype.computeWorldMatrix = function (force) {
  17999. return BABYLON.Matrix.Identity();
  18000. };
  18001. /**
  18002. * Releases resources associated with this node.
  18003. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18004. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18005. */
  18006. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18007. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18008. if (!doNotRecurse) {
  18009. var nodes = this.getDescendants(true);
  18010. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18011. var node = nodes_1[_i];
  18012. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18013. }
  18014. }
  18015. else {
  18016. var transformNodes = this.getChildTransformNodes(true);
  18017. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18018. var transformNode = transformNodes_1[_a];
  18019. transformNode.parent = null;
  18020. transformNode.computeWorldMatrix(true);
  18021. }
  18022. }
  18023. this.parent = null;
  18024. // Callback
  18025. this.onDisposeObservable.notifyObservers(this);
  18026. this.onDisposeObservable.clear();
  18027. // Behaviors
  18028. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18029. var behavior = _c[_b];
  18030. behavior.detach();
  18031. }
  18032. this._behaviors = [];
  18033. this._isDisposed = true;
  18034. };
  18035. /**
  18036. * Parse animation range data from a serialization object and store them into a given node
  18037. * @param node defines where to store the animation ranges
  18038. * @param parsedNode defines the serialization object to read data from
  18039. * @param scene defines the hosting scene
  18040. */
  18041. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18042. if (parsedNode.ranges) {
  18043. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18044. var data = parsedNode.ranges[index];
  18045. node.createAnimationRange(data.name, data.from, data.to);
  18046. }
  18047. }
  18048. };
  18049. Node._NodeConstructors = {};
  18050. __decorate([
  18051. BABYLON.serialize()
  18052. ], Node.prototype, "name", void 0);
  18053. __decorate([
  18054. BABYLON.serialize()
  18055. ], Node.prototype, "id", void 0);
  18056. __decorate([
  18057. BABYLON.serialize()
  18058. ], Node.prototype, "uniqueId", void 0);
  18059. __decorate([
  18060. BABYLON.serialize()
  18061. ], Node.prototype, "state", void 0);
  18062. __decorate([
  18063. BABYLON.serialize()
  18064. ], Node.prototype, "metadata", void 0);
  18065. return Node;
  18066. }());
  18067. BABYLON.Node = Node;
  18068. })(BABYLON || (BABYLON = {}));
  18069. //# sourceMappingURL=babylon.node.js.map
  18070. var BABYLON;
  18071. (function (BABYLON) {
  18072. var BoundingSphere = /** @class */ (function () {
  18073. /**
  18074. * Creates a new bounding sphere
  18075. * @param min defines the minimum vector (in local space)
  18076. * @param max defines the maximum vector (in local space)
  18077. */
  18078. function BoundingSphere(min, max) {
  18079. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18080. this.reConstruct(min, max);
  18081. }
  18082. /**
  18083. * Recreates the entire bounding sphere from scratch
  18084. * @param min defines the new minimum vector (in local space)
  18085. * @param max defines the new maximum vector (in local space)
  18086. */
  18087. BoundingSphere.prototype.reConstruct = function (min, max) {
  18088. this.minimum = min.clone();
  18089. this.maximum = max.clone();
  18090. var distance = BABYLON.Vector3.Distance(min, max);
  18091. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18092. this.radius = distance * 0.5;
  18093. this.centerWorld = BABYLON.Vector3.Zero();
  18094. this._update(BABYLON.Matrix.Identity());
  18095. };
  18096. /**
  18097. * Scale the current bounding sphere by applying a scale factor
  18098. * @param factor defines the scale factor to apply
  18099. * @returns the current bounding box
  18100. */
  18101. BoundingSphere.prototype.scale = function (factor) {
  18102. var newRadius = this.radius * factor;
  18103. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  18104. var min = this.center.subtract(newRadiusVector);
  18105. var max = this.center.add(newRadiusVector);
  18106. this.reConstruct(min, max);
  18107. return this;
  18108. };
  18109. // Methods
  18110. /** @hidden */
  18111. BoundingSphere.prototype._update = function (world) {
  18112. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18113. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18114. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18115. };
  18116. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18117. for (var i = 0; i < 6; i++) {
  18118. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18119. return false;
  18120. }
  18121. return true;
  18122. };
  18123. BoundingSphere.prototype.intersectsPoint = function (point) {
  18124. var x = this.centerWorld.x - point.x;
  18125. var y = this.centerWorld.y - point.y;
  18126. var z = this.centerWorld.z - point.z;
  18127. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18128. if (this.radiusWorld < distance)
  18129. return false;
  18130. return true;
  18131. };
  18132. // Statics
  18133. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18134. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18135. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18136. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18137. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18138. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18139. return false;
  18140. return true;
  18141. };
  18142. return BoundingSphere;
  18143. }());
  18144. BABYLON.BoundingSphere = BoundingSphere;
  18145. })(BABYLON || (BABYLON = {}));
  18146. //# sourceMappingURL=babylon.boundingSphere.js.map
  18147. var BABYLON;
  18148. (function (BABYLON) {
  18149. var BoundingBox = /** @class */ (function () {
  18150. /**
  18151. * Creates a new bounding box
  18152. * @param min defines the minimum vector (in local space)
  18153. * @param max defines the maximum vector (in local space)
  18154. */
  18155. function BoundingBox(min, max) {
  18156. this.vectorsWorld = new Array();
  18157. this.reConstruct(min, max);
  18158. }
  18159. // Methods
  18160. /**
  18161. * Recreates the entire bounding box from scratch
  18162. * @param min defines the new minimum vector (in local space)
  18163. * @param max defines the new maximum vector (in local space)
  18164. */
  18165. BoundingBox.prototype.reConstruct = function (min, max) {
  18166. this.minimum = min.clone();
  18167. this.maximum = max.clone();
  18168. // Bounding vectors
  18169. this.vectors = new Array();
  18170. this.vectors.push(this.minimum.clone());
  18171. this.vectors.push(this.maximum.clone());
  18172. this.vectors.push(this.minimum.clone());
  18173. this.vectors[2].x = this.maximum.x;
  18174. this.vectors.push(this.minimum.clone());
  18175. this.vectors[3].y = this.maximum.y;
  18176. this.vectors.push(this.minimum.clone());
  18177. this.vectors[4].z = this.maximum.z;
  18178. this.vectors.push(this.maximum.clone());
  18179. this.vectors[5].z = this.minimum.z;
  18180. this.vectors.push(this.maximum.clone());
  18181. this.vectors[6].x = this.minimum.x;
  18182. this.vectors.push(this.maximum.clone());
  18183. this.vectors[7].y = this.minimum.y;
  18184. // OBB
  18185. this.center = this.maximum.add(this.minimum).scale(0.5);
  18186. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18187. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18188. // World
  18189. for (var index = 0; index < this.vectors.length; index++) {
  18190. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18191. }
  18192. this.minimumWorld = BABYLON.Vector3.Zero();
  18193. this.maximumWorld = BABYLON.Vector3.Zero();
  18194. this.centerWorld = BABYLON.Vector3.Zero();
  18195. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18196. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18197. };
  18198. /**
  18199. * Scale the current bounding box by applying a scale factor
  18200. * @param factor defines the scale factor to apply
  18201. * @returns the current bounding box
  18202. */
  18203. BoundingBox.prototype.scale = function (factor) {
  18204. var diff = this.maximum.subtract(this.minimum);
  18205. var distance = diff.length() * factor;
  18206. diff.normalize();
  18207. var newRadius = diff.scale(distance / 2);
  18208. var min = this.center.subtract(newRadius);
  18209. var max = this.center.add(newRadius);
  18210. this.reConstruct(min, max);
  18211. return this;
  18212. };
  18213. BoundingBox.prototype.getWorldMatrix = function () {
  18214. return this._worldMatrix;
  18215. };
  18216. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18217. this._worldMatrix.copyFrom(matrix);
  18218. return this;
  18219. };
  18220. /** @hidden */
  18221. BoundingBox.prototype._update = function (world) {
  18222. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18223. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18224. for (var index = 0; index < this.vectors.length; index++) {
  18225. var v = this.vectorsWorld[index];
  18226. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18227. if (v.x < this.minimumWorld.x)
  18228. this.minimumWorld.x = v.x;
  18229. if (v.y < this.minimumWorld.y)
  18230. this.minimumWorld.y = v.y;
  18231. if (v.z < this.minimumWorld.z)
  18232. this.minimumWorld.z = v.z;
  18233. if (v.x > this.maximumWorld.x)
  18234. this.maximumWorld.x = v.x;
  18235. if (v.y > this.maximumWorld.y)
  18236. this.maximumWorld.y = v.y;
  18237. if (v.z > this.maximumWorld.z)
  18238. this.maximumWorld.z = v.z;
  18239. }
  18240. // Extend
  18241. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18242. this.extendSizeWorld.scaleInPlace(0.5);
  18243. // OBB
  18244. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18245. this.centerWorld.scaleInPlace(0.5);
  18246. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18247. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18248. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18249. this._worldMatrix = world;
  18250. };
  18251. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18252. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18253. };
  18254. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18255. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18256. };
  18257. BoundingBox.prototype.intersectsPoint = function (point) {
  18258. var delta = -BABYLON.Epsilon;
  18259. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18260. return false;
  18261. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18262. return false;
  18263. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18264. return false;
  18265. return true;
  18266. };
  18267. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18268. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18269. };
  18270. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18271. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18272. return false;
  18273. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18274. return false;
  18275. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18276. return false;
  18277. return true;
  18278. };
  18279. // Statics
  18280. BoundingBox.Intersects = function (box0, box1) {
  18281. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18282. return false;
  18283. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18284. return false;
  18285. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18286. return false;
  18287. return true;
  18288. };
  18289. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18290. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18291. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18292. return (num <= (sphereRadius * sphereRadius));
  18293. };
  18294. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18295. for (var p = 0; p < 6; p++) {
  18296. for (var i = 0; i < 8; i++) {
  18297. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18298. return false;
  18299. }
  18300. }
  18301. }
  18302. return true;
  18303. };
  18304. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18305. for (var p = 0; p < 6; p++) {
  18306. var inCount = 8;
  18307. for (var i = 0; i < 8; i++) {
  18308. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18309. --inCount;
  18310. }
  18311. else {
  18312. break;
  18313. }
  18314. }
  18315. if (inCount === 0)
  18316. return false;
  18317. }
  18318. return true;
  18319. };
  18320. return BoundingBox;
  18321. }());
  18322. BABYLON.BoundingBox = BoundingBox;
  18323. })(BABYLON || (BABYLON = {}));
  18324. //# sourceMappingURL=babylon.boundingBox.js.map
  18325. var BABYLON;
  18326. (function (BABYLON) {
  18327. var computeBoxExtents = function (axis, box) {
  18328. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18329. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18330. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18331. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18332. var r = r0 + r1 + r2;
  18333. return {
  18334. min: p - r,
  18335. max: p + r
  18336. };
  18337. };
  18338. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18339. var axisOverlap = function (axis, box0, box1) {
  18340. var result0 = computeBoxExtents(axis, box0);
  18341. var result1 = computeBoxExtents(axis, box1);
  18342. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18343. };
  18344. var BoundingInfo = /** @class */ (function () {
  18345. function BoundingInfo(minimum, maximum) {
  18346. this.minimum = minimum;
  18347. this.maximum = maximum;
  18348. this._isLocked = false;
  18349. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18350. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18351. }
  18352. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18353. get: function () {
  18354. return this._isLocked;
  18355. },
  18356. set: function (value) {
  18357. this._isLocked = value;
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. // Methods
  18363. BoundingInfo.prototype.update = function (world) {
  18364. if (this._isLocked) {
  18365. return;
  18366. }
  18367. this.boundingBox._update(world);
  18368. this.boundingSphere._update(world);
  18369. };
  18370. /**
  18371. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18372. * @param center New center of the bounding info
  18373. * @param extend New extend of the bounding info
  18374. */
  18375. BoundingInfo.prototype.centerOn = function (center, extend) {
  18376. this.minimum = center.subtract(extend);
  18377. this.maximum = center.add(extend);
  18378. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18379. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18380. return this;
  18381. };
  18382. /**
  18383. * Scale the current bounding info by applying a scale factor
  18384. * @param factor defines the scale factor to apply
  18385. * @returns the current bounding info
  18386. */
  18387. BoundingInfo.prototype.scale = function (factor) {
  18388. this.boundingBox.scale(factor);
  18389. this.boundingSphere.scale(factor);
  18390. return this;
  18391. };
  18392. /**
  18393. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18394. * @param frustumPlanes defines the frustum to test
  18395. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18396. * @returns true if the bounding info is in the frustum planes
  18397. */
  18398. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18399. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18400. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18401. return false;
  18402. }
  18403. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18404. return true;
  18405. }
  18406. return this.boundingBox.isInFrustum(frustumPlanes);
  18407. };
  18408. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18409. /**
  18410. * Gets the world distance between the min and max points of the bounding box
  18411. */
  18412. get: function () {
  18413. var boundingBox = this.boundingBox;
  18414. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18415. return size.length();
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18421. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18422. };
  18423. /** @hidden */
  18424. BoundingInfo.prototype._checkCollision = function (collider) {
  18425. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18426. };
  18427. BoundingInfo.prototype.intersectsPoint = function (point) {
  18428. if (!this.boundingSphere.centerWorld) {
  18429. return false;
  18430. }
  18431. if (!this.boundingSphere.intersectsPoint(point)) {
  18432. return false;
  18433. }
  18434. if (!this.boundingBox.intersectsPoint(point)) {
  18435. return false;
  18436. }
  18437. return true;
  18438. };
  18439. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18440. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18441. return false;
  18442. }
  18443. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18444. return false;
  18445. }
  18446. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18447. return false;
  18448. }
  18449. if (!precise) {
  18450. return true;
  18451. }
  18452. var box0 = this.boundingBox;
  18453. var box1 = boundingInfo.boundingBox;
  18454. if (!axisOverlap(box0.directions[0], box0, box1))
  18455. return false;
  18456. if (!axisOverlap(box0.directions[1], box0, box1))
  18457. return false;
  18458. if (!axisOverlap(box0.directions[2], box0, box1))
  18459. return false;
  18460. if (!axisOverlap(box1.directions[0], box0, box1))
  18461. return false;
  18462. if (!axisOverlap(box1.directions[1], box0, box1))
  18463. return false;
  18464. if (!axisOverlap(box1.directions[2], box0, box1))
  18465. return false;
  18466. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18467. return false;
  18468. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18469. return false;
  18470. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18471. return false;
  18472. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18473. return false;
  18474. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18475. return false;
  18476. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18477. return false;
  18478. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18479. return false;
  18480. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18481. return false;
  18482. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18483. return false;
  18484. return true;
  18485. };
  18486. return BoundingInfo;
  18487. }());
  18488. BABYLON.BoundingInfo = BoundingInfo;
  18489. })(BABYLON || (BABYLON = {}));
  18490. //# sourceMappingURL=babylon.boundingInfo.js.map
  18491. var BABYLON;
  18492. (function (BABYLON) {
  18493. var TransformNode = /** @class */ (function (_super) {
  18494. __extends(TransformNode, _super);
  18495. function TransformNode(name, scene, isPure) {
  18496. if (scene === void 0) { scene = null; }
  18497. if (isPure === void 0) { isPure = true; }
  18498. var _this = _super.call(this, name, scene) || this;
  18499. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18500. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18501. _this._up = new BABYLON.Vector3(0, 1, 0);
  18502. _this._right = new BABYLON.Vector3(1, 0, 0);
  18503. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18504. // Properties
  18505. _this._rotation = BABYLON.Vector3.Zero();
  18506. _this._scaling = BABYLON.Vector3.One();
  18507. _this._isDirty = false;
  18508. /**
  18509. * Set the billboard mode. Default is 0.
  18510. *
  18511. * | Value | Type | Description |
  18512. * | --- | --- | --- |
  18513. * | 0 | BILLBOARDMODE_NONE | |
  18514. * | 1 | BILLBOARDMODE_X | |
  18515. * | 2 | BILLBOARDMODE_Y | |
  18516. * | 4 | BILLBOARDMODE_Z | |
  18517. * | 7 | BILLBOARDMODE_ALL | |
  18518. *
  18519. */
  18520. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18521. _this.scalingDeterminant = 1;
  18522. _this.infiniteDistance = false;
  18523. /**
  18524. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18525. * By default the system will update normals to compensate
  18526. */
  18527. _this.ignoreNonUniformScaling = false;
  18528. _this.position = BABYLON.Vector3.Zero();
  18529. _this._localWorld = BABYLON.Matrix.Zero();
  18530. /** @hidden */
  18531. _this._worldMatrix = BABYLON.Matrix.Zero();
  18532. /** @hidden */
  18533. _this._worldMatrixDeterminant = 0;
  18534. _this._absolutePosition = BABYLON.Vector3.Zero();
  18535. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18536. _this._postMultiplyPivotMatrix = false;
  18537. _this._isWorldMatrixFrozen = false;
  18538. /**
  18539. * An event triggered after the world matrix is updated
  18540. */
  18541. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18542. _this._nonUniformScaling = false;
  18543. if (isPure) {
  18544. _this.getScene().addTransformNode(_this);
  18545. }
  18546. return _this;
  18547. }
  18548. /**
  18549. * Gets a string identifying the name of the class
  18550. * @returns "TransformNode" string
  18551. */
  18552. TransformNode.prototype.getClassName = function () {
  18553. return "TransformNode";
  18554. };
  18555. Object.defineProperty(TransformNode.prototype, "rotation", {
  18556. /**
  18557. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18558. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18559. * Default : (0.0, 0.0, 0.0)
  18560. */
  18561. get: function () {
  18562. return this._rotation;
  18563. },
  18564. set: function (newRotation) {
  18565. this._rotation = newRotation;
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. Object.defineProperty(TransformNode.prototype, "scaling", {
  18571. /**
  18572. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18573. * Default : (1.0, 1.0, 1.0)
  18574. */
  18575. get: function () {
  18576. return this._scaling;
  18577. },
  18578. /**
  18579. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18580. * Default : (1.0, 1.0, 1.0)
  18581. */
  18582. set: function (newScaling) {
  18583. this._scaling = newScaling;
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18589. /**
  18590. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18591. * It's null by default.
  18592. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18593. */
  18594. get: function () {
  18595. return this._rotationQuaternion;
  18596. },
  18597. set: function (quaternion) {
  18598. this._rotationQuaternion = quaternion;
  18599. //reset the rotation vector.
  18600. if (quaternion && this.rotation.length()) {
  18601. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18602. }
  18603. },
  18604. enumerable: true,
  18605. configurable: true
  18606. });
  18607. Object.defineProperty(TransformNode.prototype, "forward", {
  18608. /**
  18609. * The forward direction of that transform in world space.
  18610. */
  18611. get: function () {
  18612. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18613. },
  18614. enumerable: true,
  18615. configurable: true
  18616. });
  18617. Object.defineProperty(TransformNode.prototype, "up", {
  18618. /**
  18619. * The up direction of that transform in world space.
  18620. */
  18621. get: function () {
  18622. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. Object.defineProperty(TransformNode.prototype, "right", {
  18628. /**
  18629. * The right direction of that transform in world space.
  18630. */
  18631. get: function () {
  18632. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18633. },
  18634. enumerable: true,
  18635. configurable: true
  18636. });
  18637. /**
  18638. * Returns the latest update of the World matrix
  18639. * Returns a Matrix.
  18640. */
  18641. TransformNode.prototype.getWorldMatrix = function () {
  18642. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18643. this.computeWorldMatrix();
  18644. }
  18645. return this._worldMatrix;
  18646. };
  18647. /** @hidden */
  18648. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18649. return this._worldMatrixDeterminant;
  18650. };
  18651. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18652. /**
  18653. * Returns directly the latest state of the mesh World matrix.
  18654. * A Matrix is returned.
  18655. */
  18656. get: function () {
  18657. return this._worldMatrix;
  18658. },
  18659. enumerable: true,
  18660. configurable: true
  18661. });
  18662. /**
  18663. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18664. * Returns the TransformNode.
  18665. */
  18666. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18667. this._poseMatrix.copyFrom(matrix);
  18668. return this;
  18669. };
  18670. /**
  18671. * Returns the mesh Pose matrix.
  18672. * Returned object : Matrix
  18673. */
  18674. TransformNode.prototype.getPoseMatrix = function () {
  18675. return this._poseMatrix;
  18676. };
  18677. /** @hidden */
  18678. TransformNode.prototype._isSynchronized = function () {
  18679. if (this._isDirty) {
  18680. return false;
  18681. }
  18682. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18683. return false;
  18684. if (this._cache.pivotMatrixUpdated) {
  18685. return false;
  18686. }
  18687. if (this.infiniteDistance) {
  18688. return false;
  18689. }
  18690. if (!this._cache.position.equals(this.position))
  18691. return false;
  18692. if (this.rotationQuaternion) {
  18693. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18694. return false;
  18695. }
  18696. if (!this._cache.rotation.equals(this.rotation))
  18697. return false;
  18698. if (!this._cache.scaling.equals(this.scaling))
  18699. return false;
  18700. return true;
  18701. };
  18702. /** @hidden */
  18703. TransformNode.prototype._initCache = function () {
  18704. _super.prototype._initCache.call(this);
  18705. this._cache.localMatrixUpdated = false;
  18706. this._cache.position = BABYLON.Vector3.Zero();
  18707. this._cache.scaling = BABYLON.Vector3.Zero();
  18708. this._cache.rotation = BABYLON.Vector3.Zero();
  18709. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18710. this._cache.billboardMode = -1;
  18711. };
  18712. TransformNode.prototype.markAsDirty = function (property) {
  18713. if (property === "rotation") {
  18714. this.rotationQuaternion = null;
  18715. }
  18716. this._currentRenderId = Number.MAX_VALUE;
  18717. this._isDirty = true;
  18718. return this;
  18719. };
  18720. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18721. /**
  18722. * Returns the current mesh absolute position.
  18723. * Returns a Vector3.
  18724. */
  18725. get: function () {
  18726. return this._absolutePosition;
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. /**
  18732. * Sets a new matrix to apply before all other transformation
  18733. * @param matrix defines the transform matrix
  18734. * @returns the current TransformNode
  18735. */
  18736. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18737. return this.setPivotMatrix(matrix, false);
  18738. };
  18739. /**
  18740. * Sets a new pivot matrix to the current node
  18741. * @param matrix defines the new pivot matrix to use
  18742. * @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
  18743. * @returns the current TransformNode
  18744. */
  18745. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18746. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18747. this._pivotMatrix = matrix.clone();
  18748. this._cache.pivotMatrixUpdated = true;
  18749. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18750. if (this._postMultiplyPivotMatrix) {
  18751. if (!this._pivotMatrixInverse) {
  18752. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18753. }
  18754. else {
  18755. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18756. }
  18757. }
  18758. return this;
  18759. };
  18760. /**
  18761. * Returns the mesh pivot matrix.
  18762. * Default : Identity.
  18763. * A Matrix is returned.
  18764. */
  18765. TransformNode.prototype.getPivotMatrix = function () {
  18766. return this._pivotMatrix;
  18767. };
  18768. /**
  18769. * Prevents the World matrix to be computed any longer.
  18770. * Returns the TransformNode.
  18771. */
  18772. TransformNode.prototype.freezeWorldMatrix = function () {
  18773. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18774. this.computeWorldMatrix(true);
  18775. this._isWorldMatrixFrozen = true;
  18776. return this;
  18777. };
  18778. /**
  18779. * Allows back the World matrix computation.
  18780. * Returns the TransformNode.
  18781. */
  18782. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18783. this._isWorldMatrixFrozen = false;
  18784. this.computeWorldMatrix(true);
  18785. return this;
  18786. };
  18787. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18788. /**
  18789. * True if the World matrix has been frozen.
  18790. * Returns a boolean.
  18791. */
  18792. get: function () {
  18793. return this._isWorldMatrixFrozen;
  18794. },
  18795. enumerable: true,
  18796. configurable: true
  18797. });
  18798. /**
  18799. * Retuns the mesh absolute position in the World.
  18800. * Returns a Vector3.
  18801. */
  18802. TransformNode.prototype.getAbsolutePosition = function () {
  18803. this.computeWorldMatrix();
  18804. return this._absolutePosition;
  18805. };
  18806. /**
  18807. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18808. * Returns the TransformNode.
  18809. */
  18810. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18811. if (!absolutePosition) {
  18812. return this;
  18813. }
  18814. var absolutePositionX;
  18815. var absolutePositionY;
  18816. var absolutePositionZ;
  18817. if (absolutePosition.x === undefined) {
  18818. if (arguments.length < 3) {
  18819. return this;
  18820. }
  18821. absolutePositionX = arguments[0];
  18822. absolutePositionY = arguments[1];
  18823. absolutePositionZ = arguments[2];
  18824. }
  18825. else {
  18826. absolutePositionX = absolutePosition.x;
  18827. absolutePositionY = absolutePosition.y;
  18828. absolutePositionZ = absolutePosition.z;
  18829. }
  18830. if (this.parent) {
  18831. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18832. invertParentWorldMatrix.invert();
  18833. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18834. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18835. }
  18836. else {
  18837. this.position.x = absolutePositionX;
  18838. this.position.y = absolutePositionY;
  18839. this.position.z = absolutePositionZ;
  18840. }
  18841. return this;
  18842. };
  18843. /**
  18844. * Sets the mesh position in its local space.
  18845. * Returns the TransformNode.
  18846. */
  18847. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18848. this.computeWorldMatrix();
  18849. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18850. return this;
  18851. };
  18852. /**
  18853. * Returns the mesh position in the local space from the current World matrix values.
  18854. * Returns a new Vector3.
  18855. */
  18856. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18857. this.computeWorldMatrix();
  18858. var invLocalWorldMatrix = this._localWorld.clone();
  18859. invLocalWorldMatrix.invert();
  18860. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18861. };
  18862. /**
  18863. * Translates the mesh along the passed Vector3 in its local space.
  18864. * Returns the TransformNode.
  18865. */
  18866. TransformNode.prototype.locallyTranslate = function (vector3) {
  18867. this.computeWorldMatrix(true);
  18868. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18869. return this;
  18870. };
  18871. /**
  18872. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18873. * @param targetPoint the position (must be in same space as current mesh) to look at
  18874. * @param yawCor optional yaw (y-axis) correction in radians
  18875. * @param pitchCor optional pitch (x-axis) correction in radians
  18876. * @param rollCor optional roll (z-axis) correction in radians
  18877. * @param space the choosen space of the target
  18878. * @returns the TransformNode.
  18879. */
  18880. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18881. if (yawCor === void 0) { yawCor = 0; }
  18882. if (pitchCor === void 0) { pitchCor = 0; }
  18883. if (rollCor === void 0) { rollCor = 0; }
  18884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18885. var dv = TransformNode._lookAtVectorCache;
  18886. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18887. targetPoint.subtractToRef(pos, dv);
  18888. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18889. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18890. var pitch = Math.atan2(dv.y, len);
  18891. if (this.rotationQuaternion) {
  18892. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18893. }
  18894. else {
  18895. this.rotation.x = pitch + pitchCor;
  18896. this.rotation.y = yaw + yawCor;
  18897. this.rotation.z = rollCor;
  18898. }
  18899. return this;
  18900. };
  18901. /**
  18902. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18903. * This Vector3 is expressed in the World space.
  18904. */
  18905. TransformNode.prototype.getDirection = function (localAxis) {
  18906. var result = BABYLON.Vector3.Zero();
  18907. this.getDirectionToRef(localAxis, result);
  18908. return result;
  18909. };
  18910. /**
  18911. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18912. * localAxis is expressed in the mesh local space.
  18913. * result is computed in the Wordl space from the mesh World matrix.
  18914. * Returns the TransformNode.
  18915. */
  18916. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18917. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18918. return this;
  18919. };
  18920. /**
  18921. * Sets a new pivot point to the current node
  18922. * @param point defines the new pivot point to use
  18923. * @param space defines if the point is in world or local space (local by default)
  18924. * @returns the current TransformNode
  18925. */
  18926. TransformNode.prototype.setPivotPoint = function (point, space) {
  18927. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18928. if (this.getScene().getRenderId() == 0) {
  18929. this.computeWorldMatrix(true);
  18930. }
  18931. var wm = this.getWorldMatrix();
  18932. if (space == BABYLON.Space.WORLD) {
  18933. var tmat = BABYLON.Tmp.Matrix[0];
  18934. wm.invertToRef(tmat);
  18935. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18936. }
  18937. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18938. };
  18939. /**
  18940. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18941. */
  18942. TransformNode.prototype.getPivotPoint = function () {
  18943. var point = BABYLON.Vector3.Zero();
  18944. this.getPivotPointToRef(point);
  18945. return point;
  18946. };
  18947. /**
  18948. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18949. * Returns the TransformNode.
  18950. */
  18951. TransformNode.prototype.getPivotPointToRef = function (result) {
  18952. result.x = -this._pivotMatrix.m[12];
  18953. result.y = -this._pivotMatrix.m[13];
  18954. result.z = -this._pivotMatrix.m[14];
  18955. return this;
  18956. };
  18957. /**
  18958. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18959. */
  18960. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18961. var point = BABYLON.Vector3.Zero();
  18962. this.getAbsolutePivotPointToRef(point);
  18963. return point;
  18964. };
  18965. /**
  18966. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18967. * Returns the TransformNode.
  18968. */
  18969. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18970. result.x = this._pivotMatrix.m[12];
  18971. result.y = this._pivotMatrix.m[13];
  18972. result.z = this._pivotMatrix.m[14];
  18973. this.getPivotPointToRef(result);
  18974. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18975. return this;
  18976. };
  18977. /**
  18978. * Defines the passed node as the parent of the current node.
  18979. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18980. * Returns the TransformNode.
  18981. */
  18982. TransformNode.prototype.setParent = function (node) {
  18983. if (!node && !this.parent) {
  18984. return this;
  18985. }
  18986. if (!node) {
  18987. var rotation = BABYLON.Tmp.Quaternion[0];
  18988. var position = BABYLON.Tmp.Vector3[0];
  18989. var scale = BABYLON.Tmp.Vector3[1];
  18990. if (this.parent && this.parent.computeWorldMatrix) {
  18991. this.parent.computeWorldMatrix(true);
  18992. }
  18993. this.computeWorldMatrix(true);
  18994. this.getWorldMatrix().decompose(scale, rotation, position);
  18995. if (this.rotationQuaternion) {
  18996. this.rotationQuaternion.copyFrom(rotation);
  18997. }
  18998. else {
  18999. rotation.toEulerAnglesToRef(this.rotation);
  19000. }
  19001. this.scaling.x = scale.x;
  19002. this.scaling.y = scale.y;
  19003. this.scaling.z = scale.z;
  19004. this.position.x = position.x;
  19005. this.position.y = position.y;
  19006. this.position.z = position.z;
  19007. }
  19008. else {
  19009. var rotation = BABYLON.Tmp.Quaternion[0];
  19010. var position = BABYLON.Tmp.Vector3[0];
  19011. var scale = BABYLON.Tmp.Vector3[1];
  19012. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19013. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19014. this.computeWorldMatrix(true);
  19015. node.computeWorldMatrix(true);
  19016. node.getWorldMatrix().invertToRef(invParentMatrix);
  19017. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19018. diffMatrix.decompose(scale, rotation, position);
  19019. if (this.rotationQuaternion) {
  19020. this.rotationQuaternion.copyFrom(rotation);
  19021. }
  19022. else {
  19023. rotation.toEulerAnglesToRef(this.rotation);
  19024. }
  19025. this.position.x = position.x;
  19026. this.position.y = position.y;
  19027. this.position.z = position.z;
  19028. this.scaling.x = scale.x;
  19029. this.scaling.y = scale.y;
  19030. this.scaling.z = scale.z;
  19031. }
  19032. this.parent = node;
  19033. return this;
  19034. };
  19035. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19036. get: function () {
  19037. return this._nonUniformScaling;
  19038. },
  19039. enumerable: true,
  19040. configurable: true
  19041. });
  19042. /** @hidden */
  19043. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19044. if (this._nonUniformScaling === value) {
  19045. return false;
  19046. }
  19047. this._nonUniformScaling = value;
  19048. return true;
  19049. };
  19050. /**
  19051. * Attach the current TransformNode to another TransformNode associated with a bone
  19052. * @param bone Bone affecting the TransformNode
  19053. * @param affectedTransformNode TransformNode associated with the bone
  19054. */
  19055. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19056. this._transformToBoneReferal = affectedTransformNode;
  19057. this.parent = bone;
  19058. if (bone.getWorldMatrix().determinant() < 0) {
  19059. this.scalingDeterminant *= -1;
  19060. }
  19061. return this;
  19062. };
  19063. TransformNode.prototype.detachFromBone = function () {
  19064. if (!this.parent) {
  19065. return this;
  19066. }
  19067. if (this.parent.getWorldMatrix().determinant() < 0) {
  19068. this.scalingDeterminant *= -1;
  19069. }
  19070. this._transformToBoneReferal = null;
  19071. this.parent = null;
  19072. return this;
  19073. };
  19074. /**
  19075. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19076. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19077. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19078. * The passed axis is also normalized.
  19079. * Returns the TransformNode.
  19080. */
  19081. TransformNode.prototype.rotate = function (axis, amount, space) {
  19082. axis.normalize();
  19083. if (!this.rotationQuaternion) {
  19084. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19085. this.rotation = BABYLON.Vector3.Zero();
  19086. }
  19087. var rotationQuaternion;
  19088. if (!space || space === BABYLON.Space.LOCAL) {
  19089. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19090. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19091. }
  19092. else {
  19093. if (this.parent) {
  19094. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19095. invertParentWorldMatrix.invert();
  19096. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19097. }
  19098. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19099. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19100. }
  19101. return this;
  19102. };
  19103. /**
  19104. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19105. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19106. * The passed axis is also normalized.
  19107. * Returns the TransformNode.
  19108. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19109. */
  19110. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19111. axis.normalize();
  19112. if (!this.rotationQuaternion) {
  19113. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19114. this.rotation.copyFromFloats(0, 0, 0);
  19115. }
  19116. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19117. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19118. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19119. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19120. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19121. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19122. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19123. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19124. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19125. return this;
  19126. };
  19127. /**
  19128. * Translates the mesh along the axis vector for the passed distance in the given space.
  19129. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19130. * Returns the TransformNode.
  19131. */
  19132. TransformNode.prototype.translate = function (axis, distance, space) {
  19133. var displacementVector = axis.scale(distance);
  19134. if (!space || space === BABYLON.Space.LOCAL) {
  19135. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19136. this.setPositionWithLocalVector(tempV3);
  19137. }
  19138. else {
  19139. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19140. }
  19141. return this;
  19142. };
  19143. /**
  19144. * Adds a rotation step to the mesh current rotation.
  19145. * x, y, z are Euler angles expressed in radians.
  19146. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19147. * This means this rotation is made in the mesh local space only.
  19148. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19149. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19150. * ```javascript
  19151. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19152. * ```
  19153. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19154. * 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.
  19155. * Returns the TransformNode.
  19156. */
  19157. TransformNode.prototype.addRotation = function (x, y, z) {
  19158. var rotationQuaternion;
  19159. if (this.rotationQuaternion) {
  19160. rotationQuaternion = this.rotationQuaternion;
  19161. }
  19162. else {
  19163. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19164. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19165. }
  19166. var accumulation = BABYLON.Tmp.Quaternion[0];
  19167. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19168. rotationQuaternion.multiplyInPlace(accumulation);
  19169. if (!this.rotationQuaternion) {
  19170. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19171. }
  19172. return this;
  19173. };
  19174. /**
  19175. * Computes the mesh World matrix and returns it.
  19176. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19177. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19178. * If the parameter `force`is set to `true`, the actual computation is done.
  19179. * Returns the mesh World Matrix.
  19180. */
  19181. TransformNode.prototype.computeWorldMatrix = function (force) {
  19182. if (this._isWorldMatrixFrozen) {
  19183. return this._worldMatrix;
  19184. }
  19185. if (!force && this.isSynchronized(true)) {
  19186. this._currentRenderId = this.getScene().getRenderId();
  19187. return this._worldMatrix;
  19188. }
  19189. this._cache.position.copyFrom(this.position);
  19190. this._cache.scaling.copyFrom(this.scaling);
  19191. this._cache.pivotMatrixUpdated = false;
  19192. this._cache.billboardMode = this.billboardMode;
  19193. this._currentRenderId = this.getScene().getRenderId();
  19194. this._childRenderId = this.getScene().getRenderId();
  19195. this._isDirty = false;
  19196. // Scaling
  19197. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19198. // Rotation
  19199. //rotate, if quaternion is set and rotation was used
  19200. if (this.rotationQuaternion) {
  19201. var len = this.rotation.length();
  19202. if (len) {
  19203. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19204. this.rotation.copyFromFloats(0, 0, 0);
  19205. }
  19206. }
  19207. if (this.rotationQuaternion) {
  19208. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19209. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19210. }
  19211. else {
  19212. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19213. this._cache.rotation.copyFrom(this.rotation);
  19214. }
  19215. // Translation
  19216. var camera = this.getScene().activeCamera;
  19217. if (this.infiniteDistance && !this.parent && camera) {
  19218. var cameraWorldMatrix = camera.getWorldMatrix();
  19219. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19220. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19221. }
  19222. else {
  19223. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19224. }
  19225. // Composing transformations
  19226. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19227. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19228. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19229. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19230. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19231. // Need to decompose each rotation here
  19232. var currentPosition = BABYLON.Tmp.Vector3[3];
  19233. if (this.parent && this.parent.getWorldMatrix) {
  19234. if (this._transformToBoneReferal) {
  19235. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19236. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19237. }
  19238. else {
  19239. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19240. }
  19241. }
  19242. else {
  19243. currentPosition.copyFrom(this.position);
  19244. }
  19245. currentPosition.subtractInPlace(camera.globalPosition);
  19246. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19247. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19248. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19249. }
  19250. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19251. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19252. }
  19253. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19254. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19255. }
  19256. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19257. }
  19258. else {
  19259. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19260. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19261. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19262. }
  19263. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19264. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19265. }
  19266. // Post multiply inverse of pivotMatrix
  19267. if (this._postMultiplyPivotMatrix) {
  19268. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19269. }
  19270. // Local world
  19271. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19272. // Parent
  19273. if (this.parent && this.parent.getWorldMatrix) {
  19274. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19275. if (this._transformToBoneReferal) {
  19276. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19277. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19278. }
  19279. else {
  19280. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19281. }
  19282. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19283. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19284. this._worldMatrix.copyFrom(this._localWorld);
  19285. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19286. }
  19287. else {
  19288. if (this._transformToBoneReferal) {
  19289. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19290. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19291. }
  19292. else {
  19293. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19294. }
  19295. }
  19296. this._markSyncedWithParent();
  19297. }
  19298. else {
  19299. this._worldMatrix.copyFrom(this._localWorld);
  19300. }
  19301. // Normal matrix
  19302. if (!this.ignoreNonUniformScaling) {
  19303. if (this.scaling.isNonUniform) {
  19304. this._updateNonUniformScalingState(true);
  19305. }
  19306. else if (this.parent && this.parent._nonUniformScaling) {
  19307. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19308. }
  19309. else {
  19310. this._updateNonUniformScalingState(false);
  19311. }
  19312. }
  19313. else {
  19314. this._updateNonUniformScalingState(false);
  19315. }
  19316. this._afterComputeWorldMatrix();
  19317. // Absolute position
  19318. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19319. // Callbacks
  19320. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19321. if (!this._poseMatrix) {
  19322. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19323. }
  19324. // Cache the determinant
  19325. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19326. return this._worldMatrix;
  19327. };
  19328. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19329. };
  19330. /**
  19331. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19332. * @param func: callback function to add
  19333. *
  19334. * Returns the TransformNode.
  19335. */
  19336. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19337. this.onAfterWorldMatrixUpdateObservable.add(func);
  19338. return this;
  19339. };
  19340. /**
  19341. * Removes a registered callback function.
  19342. * Returns the TransformNode.
  19343. */
  19344. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19345. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19346. return this;
  19347. };
  19348. /**
  19349. * Clone the current transform node
  19350. * Returns the new transform node
  19351. * @param name Name of the new clone
  19352. * @param newParent New parent for the clone
  19353. * @param doNotCloneChildren Do not clone children hierarchy
  19354. */
  19355. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19356. var _this = this;
  19357. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19358. result.name = name;
  19359. result.id = name;
  19360. if (newParent) {
  19361. result.parent = newParent;
  19362. }
  19363. if (!doNotCloneChildren) {
  19364. // Children
  19365. var directDescendants = this.getDescendants(true);
  19366. for (var index = 0; index < directDescendants.length; index++) {
  19367. var child = directDescendants[index];
  19368. if (child.clone) {
  19369. child.clone(name + "." + child.name, result);
  19370. }
  19371. }
  19372. }
  19373. return result;
  19374. };
  19375. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19376. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19377. serializationObject.type = this.getClassName();
  19378. // Parent
  19379. if (this.parent) {
  19380. serializationObject.parentId = this.parent.id;
  19381. }
  19382. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19383. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19384. }
  19385. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19386. serializationObject.isEnabled = this.isEnabled();
  19387. // Parent
  19388. if (this.parent) {
  19389. serializationObject.parentId = this.parent.id;
  19390. }
  19391. return serializationObject;
  19392. };
  19393. // Statics
  19394. /**
  19395. * Returns a new TransformNode object parsed from the source provided.
  19396. * The parameter `parsedMesh` is the source.
  19397. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19398. */
  19399. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19400. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19401. if (BABYLON.Tags) {
  19402. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19403. }
  19404. if (parsedTransformNode.localMatrix) {
  19405. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19406. }
  19407. else if (parsedTransformNode.pivotMatrix) {
  19408. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19409. }
  19410. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19411. // Parent
  19412. if (parsedTransformNode.parentId) {
  19413. transformNode._waitingParentId = parsedTransformNode.parentId;
  19414. }
  19415. return transformNode;
  19416. };
  19417. /**
  19418. * Releases resources associated with this transform node.
  19419. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19420. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19421. */
  19422. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19423. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19424. // Animations
  19425. this.getScene().stopAnimation(this);
  19426. // Remove from scene
  19427. this.getScene().removeTransformNode(this);
  19428. this.onAfterWorldMatrixUpdateObservable.clear();
  19429. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19430. };
  19431. // Statics
  19432. TransformNode.BILLBOARDMODE_NONE = 0;
  19433. TransformNode.BILLBOARDMODE_X = 1;
  19434. TransformNode.BILLBOARDMODE_Y = 2;
  19435. TransformNode.BILLBOARDMODE_Z = 4;
  19436. TransformNode.BILLBOARDMODE_ALL = 7;
  19437. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19438. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19439. __decorate([
  19440. BABYLON.serializeAsVector3()
  19441. ], TransformNode.prototype, "_rotation", void 0);
  19442. __decorate([
  19443. BABYLON.serializeAsQuaternion()
  19444. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19445. __decorate([
  19446. BABYLON.serializeAsVector3()
  19447. ], TransformNode.prototype, "_scaling", void 0);
  19448. __decorate([
  19449. BABYLON.serialize()
  19450. ], TransformNode.prototype, "billboardMode", void 0);
  19451. __decorate([
  19452. BABYLON.serialize()
  19453. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19454. __decorate([
  19455. BABYLON.serialize()
  19456. ], TransformNode.prototype, "infiniteDistance", void 0);
  19457. __decorate([
  19458. BABYLON.serialize()
  19459. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19460. __decorate([
  19461. BABYLON.serializeAsVector3()
  19462. ], TransformNode.prototype, "position", void 0);
  19463. return TransformNode;
  19464. }(BABYLON.Node));
  19465. BABYLON.TransformNode = TransformNode;
  19466. })(BABYLON || (BABYLON = {}));
  19467. //# sourceMappingURL=babylon.transformNode.js.map
  19468. var BABYLON;
  19469. (function (BABYLON) {
  19470. /**
  19471. * Class used to store all common mesh properties
  19472. */
  19473. var AbstractMesh = /** @class */ (function (_super) {
  19474. __extends(AbstractMesh, _super);
  19475. // Constructor
  19476. /**
  19477. * Creates a new AbstractMesh
  19478. * @param name defines the name of the mesh
  19479. * @param scene defines the hosting scene
  19480. */
  19481. function AbstractMesh(name, scene) {
  19482. if (scene === void 0) { scene = null; }
  19483. var _this = _super.call(this, name, scene, false) || this;
  19484. _this._facetNb = 0; // facet number
  19485. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19486. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19487. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19488. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19489. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19490. _this._subDiv = {
  19491. max: 1,
  19492. X: 1,
  19493. Y: 1,
  19494. Z: 1
  19495. };
  19496. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19497. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19498. /** Gets ot sets the culling strategy to use to find visible meshes */
  19499. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19500. // Events
  19501. /**
  19502. * An event triggered when this mesh collides with another one
  19503. */
  19504. _this.onCollideObservable = new BABYLON.Observable();
  19505. /**
  19506. * An event triggered when the collision's position changes
  19507. */
  19508. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19509. /**
  19510. * An event triggered when material is changed
  19511. */
  19512. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19513. // Properties
  19514. /**
  19515. * Gets or sets the orientation for POV movement & rotation
  19516. */
  19517. _this.definedFacingForward = true;
  19518. /**
  19519. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19520. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19521. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19522. * @see http://doc.babylonjs.com/features/occlusionquery
  19523. */
  19524. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19525. /**
  19526. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19527. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19528. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19529. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19530. * @see http://doc.babylonjs.com/features/occlusionquery
  19531. */
  19532. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19533. /**
  19534. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19535. * The default value is -1 which means don't break the query and wait till the result
  19536. * @see http://doc.babylonjs.com/features/occlusionquery
  19537. */
  19538. _this.occlusionRetryCount = -1;
  19539. /** @hidden */
  19540. _this._occlusionInternalRetryCounter = 0;
  19541. /** @hidden */
  19542. _this._isOccluded = false;
  19543. /** @hidden */
  19544. _this._isOcclusionQueryInProgress = false;
  19545. _this._visibility = 1.0;
  19546. /** Gets or sets the alpha index used to sort transparent meshes
  19547. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19548. */
  19549. _this.alphaIndex = Number.MAX_VALUE;
  19550. /**
  19551. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19552. */
  19553. _this.isVisible = true;
  19554. /**
  19555. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19556. */
  19557. _this.isPickable = true;
  19558. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19559. _this.showSubMeshesBoundingBox = false;
  19560. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19561. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19562. */
  19563. _this.isBlocker = false;
  19564. /**
  19565. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19566. */
  19567. _this.enablePointerMoveEvents = false;
  19568. /**
  19569. * Specifies the rendering group id for this mesh (0 by default)
  19570. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19571. */
  19572. _this.renderingGroupId = 0;
  19573. _this._receiveShadows = false;
  19574. /**
  19575. * Gets or sets a boolean indicating if the outline must be rendered as well
  19576. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19577. */
  19578. _this.renderOutline = false;
  19579. /** Defines color to use when rendering outline */
  19580. _this.outlineColor = BABYLON.Color3.Red();
  19581. /** Define width to use when rendering outline */
  19582. _this.outlineWidth = 0.02;
  19583. /**
  19584. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19585. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19586. */
  19587. _this.renderOverlay = false;
  19588. /** Defines color to use when rendering overlay */
  19589. _this.overlayColor = BABYLON.Color3.Red();
  19590. /** Defines alpha to use when rendering overlay */
  19591. _this.overlayAlpha = 0.5;
  19592. _this._hasVertexAlpha = false;
  19593. _this._useVertexColors = true;
  19594. _this._computeBonesUsingShaders = true;
  19595. _this._numBoneInfluencers = 4;
  19596. _this._applyFog = true;
  19597. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19598. _this.useOctreeForRenderingSelection = true;
  19599. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19600. _this.useOctreeForPicking = true;
  19601. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19602. _this.useOctreeForCollisions = true;
  19603. _this._layerMask = 0x0FFFFFFF;
  19604. /**
  19605. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19606. */
  19607. _this.alwaysSelectAsActiveMesh = false;
  19608. /**
  19609. * Gets or sets the current action manager
  19610. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19611. */
  19612. _this.actionManager = null;
  19613. /**
  19614. * Gets or sets impostor used for physic simulation
  19615. * @see http://doc.babylonjs.com/features/physics_engine
  19616. */
  19617. _this.physicsImpostor = null;
  19618. // Collisions
  19619. _this._checkCollisions = false;
  19620. _this._collisionMask = -1;
  19621. _this._collisionGroup = -1;
  19622. /**
  19623. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19624. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19625. */
  19626. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19627. /**
  19628. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19629. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19630. */
  19631. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19632. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19633. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19634. // Edges
  19635. /**
  19636. * Defines edge width used when edgesRenderer is enabled
  19637. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19638. */
  19639. _this.edgesWidth = 1;
  19640. /**
  19641. * Defines edge color used when edgesRenderer is enabled
  19642. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19643. */
  19644. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19645. // Cache
  19646. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19647. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19648. /** @hidden */
  19649. _this._renderId = 0;
  19650. /** @hidden */
  19651. _this._intersectionsInProgress = new Array();
  19652. /** @hidden */
  19653. _this._unIndexed = false;
  19654. /** @hidden */
  19655. _this._lightSources = new Array();
  19656. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19657. if (collidedMesh === void 0) { collidedMesh = null; }
  19658. //TODO move this to the collision coordinator!
  19659. if (_this.getScene().workerCollisions)
  19660. newPosition.multiplyInPlace(_this._collider._radius);
  19661. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19662. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19663. _this.position.addInPlace(_this._diffPositionForCollisions);
  19664. }
  19665. if (collidedMesh) {
  19666. _this.onCollideObservable.notifyObservers(collidedMesh);
  19667. }
  19668. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19669. };
  19670. _this.getScene().addMesh(_this);
  19671. _this._resyncLightSources();
  19672. return _this;
  19673. }
  19674. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19675. /**
  19676. * No billboard
  19677. */
  19678. get: function () {
  19679. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19685. /** Billboard on X axis */
  19686. get: function () {
  19687. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19693. /** Billboard on Y axis */
  19694. get: function () {
  19695. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19701. /** Billboard on Z axis */
  19702. get: function () {
  19703. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19709. /** Billboard on all axes */
  19710. get: function () {
  19711. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19717. /**
  19718. * Gets the number of facets in the mesh
  19719. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19720. */
  19721. get: function () {
  19722. return this._facetNb;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19728. /**
  19729. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19730. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19731. */
  19732. get: function () {
  19733. return this._partitioningSubdivisions;
  19734. },
  19735. set: function (nb) {
  19736. this._partitioningSubdivisions = nb;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19742. /**
  19743. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19744. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19745. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19746. */
  19747. get: function () {
  19748. return this._partitioningBBoxRatio;
  19749. },
  19750. set: function (ratio) {
  19751. this._partitioningBBoxRatio = ratio;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19757. /**
  19758. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19759. * Works only for updatable meshes.
  19760. * Doesn't work with multi-materials
  19761. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19762. */
  19763. get: function () {
  19764. return this._facetDepthSort;
  19765. },
  19766. set: function (sort) {
  19767. this._facetDepthSort = sort;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19773. /**
  19774. * The location (Vector3) where the facet depth sort must be computed from.
  19775. * By default, the active camera position.
  19776. * Used only when facet depth sort is enabled
  19777. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19778. */
  19779. get: function () {
  19780. return this._facetDepthSortFrom;
  19781. },
  19782. set: function (location) {
  19783. this._facetDepthSortFrom = location;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19789. /**
  19790. * gets a boolean indicating if facetData is enabled
  19791. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19792. */
  19793. get: function () {
  19794. return this._facetDataEnabled;
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. /** @hidden */
  19800. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19801. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19802. return false;
  19803. }
  19804. this._markSubMeshesAsMiscDirty();
  19805. return true;
  19806. };
  19807. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19808. /** Set a function to call when this mesh collides with another one */
  19809. set: function (callback) {
  19810. if (this._onCollideObserver) {
  19811. this.onCollideObservable.remove(this._onCollideObserver);
  19812. }
  19813. this._onCollideObserver = this.onCollideObservable.add(callback);
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19819. /** Set a function to call when the collision's position changes */
  19820. set: function (callback) {
  19821. if (this._onCollisionPositionChangeObserver) {
  19822. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19823. }
  19824. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19830. /**
  19831. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19832. * @see http://doc.babylonjs.com/features/occlusionquery
  19833. */
  19834. get: function () {
  19835. return this._isOccluded;
  19836. },
  19837. set: function (value) {
  19838. this._isOccluded = value;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19844. /**
  19845. * Flag to check the progress status of the query
  19846. * @see http://doc.babylonjs.com/features/occlusionquery
  19847. */
  19848. get: function () {
  19849. return this._isOcclusionQueryInProgress;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19855. /**
  19856. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19857. */
  19858. get: function () {
  19859. return this._visibility;
  19860. },
  19861. /**
  19862. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19863. */
  19864. set: function (value) {
  19865. if (this._visibility === value) {
  19866. return;
  19867. }
  19868. this._visibility = value;
  19869. this._markSubMeshesAsMiscDirty();
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(AbstractMesh.prototype, "material", {
  19875. /** Gets or sets current material */
  19876. get: function () {
  19877. return this._material;
  19878. },
  19879. set: function (value) {
  19880. if (this._material === value) {
  19881. return;
  19882. }
  19883. this._material = value;
  19884. if (this.onMaterialChangedObservable.hasObservers) {
  19885. this.onMaterialChangedObservable.notifyObservers(this);
  19886. }
  19887. if (!this.subMeshes) {
  19888. return;
  19889. }
  19890. this._unBindEffect();
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19896. /**
  19897. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19898. * @see http://doc.babylonjs.com/babylon101/shadows
  19899. */
  19900. get: function () {
  19901. return this._receiveShadows;
  19902. },
  19903. set: function (value) {
  19904. if (this._receiveShadows === value) {
  19905. return;
  19906. }
  19907. this._receiveShadows = value;
  19908. this._markSubMeshesAsLightDirty();
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19914. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19915. get: function () {
  19916. return this._hasVertexAlpha;
  19917. },
  19918. set: function (value) {
  19919. if (this._hasVertexAlpha === value) {
  19920. return;
  19921. }
  19922. this._hasVertexAlpha = value;
  19923. this._markSubMeshesAsAttributesDirty();
  19924. this._markSubMeshesAsMiscDirty();
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19930. /** 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) */
  19931. get: function () {
  19932. return this._useVertexColors;
  19933. },
  19934. set: function (value) {
  19935. if (this._useVertexColors === value) {
  19936. return;
  19937. }
  19938. this._useVertexColors = value;
  19939. this._markSubMeshesAsAttributesDirty();
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19945. /**
  19946. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19947. */
  19948. get: function () {
  19949. return this._computeBonesUsingShaders;
  19950. },
  19951. set: function (value) {
  19952. if (this._computeBonesUsingShaders === value) {
  19953. return;
  19954. }
  19955. this._computeBonesUsingShaders = value;
  19956. this._markSubMeshesAsAttributesDirty();
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19962. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19963. get: function () {
  19964. return this._numBoneInfluencers;
  19965. },
  19966. set: function (value) {
  19967. if (this._numBoneInfluencers === value) {
  19968. return;
  19969. }
  19970. this._numBoneInfluencers = value;
  19971. this._markSubMeshesAsAttributesDirty();
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19977. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19978. get: function () {
  19979. return this._applyFog;
  19980. },
  19981. set: function (value) {
  19982. if (this._applyFog === value) {
  19983. return;
  19984. }
  19985. this._applyFog = value;
  19986. this._markSubMeshesAsMiscDirty();
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19992. /**
  19993. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19994. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19995. */
  19996. get: function () {
  19997. return this._layerMask;
  19998. },
  19999. set: function (value) {
  20000. if (value === this._layerMask) {
  20001. return;
  20002. }
  20003. this._layerMask = value;
  20004. this._resyncLightSources();
  20005. },
  20006. enumerable: true,
  20007. configurable: true
  20008. });
  20009. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20010. /**
  20011. * Gets or sets a collision mask used to mask collisions (default is -1).
  20012. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20013. */
  20014. get: function () {
  20015. return this._collisionMask;
  20016. },
  20017. set: function (mask) {
  20018. this._collisionMask = !isNaN(mask) ? mask : -1;
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20024. /**
  20025. * Gets or sets the current collision group mask (-1 by default).
  20026. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20027. */
  20028. get: function () {
  20029. return this._collisionGroup;
  20030. },
  20031. set: function (mask) {
  20032. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20038. /** @hidden */
  20039. get: function () {
  20040. return null;
  20041. },
  20042. enumerable: true,
  20043. configurable: true
  20044. });
  20045. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20046. get: function () {
  20047. return this._skeleton;
  20048. },
  20049. /**
  20050. * Gets or sets a skeleton to apply skining transformations
  20051. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20052. */
  20053. set: function (value) {
  20054. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20055. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20056. }
  20057. if (value && value.needInitialSkinMatrix) {
  20058. value._registerMeshWithPoseMatrix(this);
  20059. }
  20060. this._skeleton = value;
  20061. if (!this._skeleton) {
  20062. this._bonesTransformMatrices = null;
  20063. }
  20064. this._markSubMeshesAsAttributesDirty();
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. /**
  20070. * Returns the string "AbstractMesh"
  20071. * @returns "AbstractMesh"
  20072. */
  20073. AbstractMesh.prototype.getClassName = function () {
  20074. return "AbstractMesh";
  20075. };
  20076. /**
  20077. * Gets a string representation of the current mesh
  20078. * @param fullDetails defines a boolean indicating if full details must be included
  20079. * @returns a string representation of the current mesh
  20080. */
  20081. AbstractMesh.prototype.toString = function (fullDetails) {
  20082. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20083. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20084. if (this._skeleton) {
  20085. ret += ", skeleton: " + this._skeleton.name;
  20086. }
  20087. if (fullDetails) {
  20088. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20089. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20090. }
  20091. return ret;
  20092. };
  20093. /** @hidden */
  20094. AbstractMesh.prototype._rebuild = function () {
  20095. if (this._occlusionQuery) {
  20096. this._occlusionQuery = null;
  20097. }
  20098. if (this._edgesRenderer) {
  20099. this._edgesRenderer._rebuild();
  20100. }
  20101. if (!this.subMeshes) {
  20102. return;
  20103. }
  20104. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20105. var subMesh = _a[_i];
  20106. subMesh._rebuild();
  20107. }
  20108. };
  20109. /** @hidden */
  20110. AbstractMesh.prototype._resyncLightSources = function () {
  20111. this._lightSources.length = 0;
  20112. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20113. var light = _a[_i];
  20114. if (!light.isEnabled()) {
  20115. continue;
  20116. }
  20117. if (light.canAffectMesh(this)) {
  20118. this._lightSources.push(light);
  20119. }
  20120. }
  20121. this._markSubMeshesAsLightDirty();
  20122. };
  20123. /** @hidden */
  20124. AbstractMesh.prototype._resyncLighSource = function (light) {
  20125. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20126. var index = this._lightSources.indexOf(light);
  20127. if (index === -1) {
  20128. if (!isIn) {
  20129. return;
  20130. }
  20131. this._lightSources.push(light);
  20132. }
  20133. else {
  20134. if (isIn) {
  20135. return;
  20136. }
  20137. this._lightSources.splice(index, 1);
  20138. }
  20139. this._markSubMeshesAsLightDirty();
  20140. };
  20141. /** @hidden */
  20142. AbstractMesh.prototype._unBindEffect = function () {
  20143. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20144. var subMesh = _a[_i];
  20145. subMesh.setEffect(null);
  20146. }
  20147. };
  20148. /** @hidden */
  20149. AbstractMesh.prototype._removeLightSource = function (light) {
  20150. var index = this._lightSources.indexOf(light);
  20151. if (index === -1) {
  20152. return;
  20153. }
  20154. this._lightSources.splice(index, 1);
  20155. this._markSubMeshesAsLightDirty();
  20156. };
  20157. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20158. if (!this.subMeshes) {
  20159. return;
  20160. }
  20161. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20162. var subMesh = _a[_i];
  20163. if (subMesh._materialDefines) {
  20164. func(subMesh._materialDefines);
  20165. }
  20166. }
  20167. };
  20168. /** @hidden */
  20169. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20170. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20171. };
  20172. /** @hidden */
  20173. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20174. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20175. };
  20176. /** @hidden */
  20177. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20178. if (!this.subMeshes) {
  20179. return;
  20180. }
  20181. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20182. var subMesh = _a[_i];
  20183. var material = subMesh.getMaterial();
  20184. if (material) {
  20185. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20186. }
  20187. }
  20188. };
  20189. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20190. /**
  20191. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20192. */
  20193. get: function () {
  20194. return this._scaling;
  20195. },
  20196. set: function (newScaling) {
  20197. this._scaling = newScaling;
  20198. if (this.physicsImpostor) {
  20199. this.physicsImpostor.forceUpdate();
  20200. }
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. // Methods
  20206. /**
  20207. * Disables the mesh edge rendering mode
  20208. * @returns the currentAbstractMesh
  20209. */
  20210. AbstractMesh.prototype.disableEdgesRendering = function () {
  20211. if (this._edgesRenderer) {
  20212. this._edgesRenderer.dispose();
  20213. this._edgesRenderer = null;
  20214. }
  20215. return this;
  20216. };
  20217. /**
  20218. * Enables the edge rendering mode on the mesh.
  20219. * This mode makes the mesh edges visible
  20220. * @param epsilon defines the maximal distance between two angles to detect a face
  20221. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20222. * @returns the currentAbstractMesh
  20223. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20224. */
  20225. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20226. if (epsilon === void 0) { epsilon = 0.95; }
  20227. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20228. this.disableEdgesRendering();
  20229. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20230. return this;
  20231. };
  20232. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20233. /**
  20234. * Gets the edgesRenderer associated with the mesh
  20235. */
  20236. get: function () {
  20237. return this._edgesRenderer;
  20238. },
  20239. enumerable: true,
  20240. configurable: true
  20241. });
  20242. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20243. /**
  20244. * Returns true if the mesh is blocked. Implemented by child classes
  20245. */
  20246. get: function () {
  20247. return false;
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. /**
  20253. * Returns the mesh itself by default. Implemented by child classes
  20254. * @param camera defines the camera to use to pick the right LOD level
  20255. * @returns the currentAbstractMesh
  20256. */
  20257. AbstractMesh.prototype.getLOD = function (camera) {
  20258. return this;
  20259. };
  20260. /**
  20261. * Returns 0 by default. Implemented by child classes
  20262. * @returns an integer
  20263. */
  20264. AbstractMesh.prototype.getTotalVertices = function () {
  20265. return 0;
  20266. };
  20267. /**
  20268. * Returns null by default. Implemented by child classes
  20269. * @returns null
  20270. */
  20271. AbstractMesh.prototype.getIndices = function () {
  20272. return null;
  20273. };
  20274. /**
  20275. * Returns the array of the requested vertex data kind. Implemented by child classes
  20276. * @param kind defines the vertex data kind to use
  20277. * @returns null
  20278. */
  20279. AbstractMesh.prototype.getVerticesData = function (kind) {
  20280. return null;
  20281. };
  20282. /**
  20283. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20284. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20285. * Note that a new underlying VertexBuffer object is created each call.
  20286. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20287. * @param kind defines vertex data kind:
  20288. * * BABYLON.VertexBuffer.PositionKind
  20289. * * BABYLON.VertexBuffer.UVKind
  20290. * * BABYLON.VertexBuffer.UV2Kind
  20291. * * BABYLON.VertexBuffer.UV3Kind
  20292. * * BABYLON.VertexBuffer.UV4Kind
  20293. * * BABYLON.VertexBuffer.UV5Kind
  20294. * * BABYLON.VertexBuffer.UV6Kind
  20295. * * BABYLON.VertexBuffer.ColorKind
  20296. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20297. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20298. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20299. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20300. * @param data defines the data source
  20301. * @param updatable defines if the data must be flagged as updatable (or static)
  20302. * @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
  20303. * @returns the current mesh
  20304. */
  20305. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20306. return this;
  20307. };
  20308. /**
  20309. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20310. * If the mesh has no geometry, it is simply returned as it is.
  20311. * @param kind defines vertex data kind:
  20312. * * BABYLON.VertexBuffer.PositionKind
  20313. * * BABYLON.VertexBuffer.UVKind
  20314. * * BABYLON.VertexBuffer.UV2Kind
  20315. * * BABYLON.VertexBuffer.UV3Kind
  20316. * * BABYLON.VertexBuffer.UV4Kind
  20317. * * BABYLON.VertexBuffer.UV5Kind
  20318. * * BABYLON.VertexBuffer.UV6Kind
  20319. * * BABYLON.VertexBuffer.ColorKind
  20320. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20321. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20322. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20323. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20324. * @param data defines the data source
  20325. * @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
  20326. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20327. * @returns the current mesh
  20328. */
  20329. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20330. return this;
  20331. };
  20332. /**
  20333. * Sets the mesh indices,
  20334. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20335. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20336. * @param totalVertices Defines the total number of vertices
  20337. * @returns the current mesh
  20338. */
  20339. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20340. return this;
  20341. };
  20342. /**
  20343. * Gets a boolean indicating if specific vertex data is present
  20344. * @param kind defines the vertex data kind to use
  20345. * @returns true is data kind is present
  20346. */
  20347. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20348. return false;
  20349. };
  20350. /**
  20351. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20352. * @returns a BoundingInfo
  20353. */
  20354. AbstractMesh.prototype.getBoundingInfo = function () {
  20355. if (this._masterMesh) {
  20356. return this._masterMesh.getBoundingInfo();
  20357. }
  20358. if (!this._boundingInfo) {
  20359. // this._boundingInfo is being created here
  20360. this._updateBoundingInfo();
  20361. }
  20362. // cannot be null.
  20363. return this._boundingInfo;
  20364. };
  20365. /**
  20366. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20367. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20368. * @returns the current mesh
  20369. */
  20370. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20371. if (includeDescendants === void 0) { includeDescendants = true; }
  20372. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20373. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20374. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20375. if (maxDimension === 0) {
  20376. return this;
  20377. }
  20378. var scale = 1 / maxDimension;
  20379. this.scaling.scaleInPlace(scale);
  20380. return this;
  20381. };
  20382. /**
  20383. * Overwrite the current bounding info
  20384. * @param boundingInfo defines the new bounding info
  20385. * @returns the current mesh
  20386. */
  20387. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20388. this._boundingInfo = boundingInfo;
  20389. return this;
  20390. };
  20391. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20392. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20393. get: function () {
  20394. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20395. },
  20396. enumerable: true,
  20397. configurable: true
  20398. });
  20399. /** @hidden */
  20400. AbstractMesh.prototype._preActivate = function () {
  20401. };
  20402. /** @hidden */
  20403. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20404. };
  20405. /** @hidden */
  20406. AbstractMesh.prototype._activate = function (renderId) {
  20407. this._renderId = renderId;
  20408. };
  20409. /**
  20410. * Gets the current world matrix
  20411. * @returns a Matrix
  20412. */
  20413. AbstractMesh.prototype.getWorldMatrix = function () {
  20414. if (this._masterMesh) {
  20415. return this._masterMesh.getWorldMatrix();
  20416. }
  20417. return _super.prototype.getWorldMatrix.call(this);
  20418. };
  20419. /** @hidden */
  20420. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20421. if (this._masterMesh) {
  20422. return this._masterMesh._getWorldMatrixDeterminant();
  20423. }
  20424. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20425. };
  20426. // ================================== Point of View Movement =================================
  20427. /**
  20428. * Perform relative position change from the point of view of behind the front of the mesh.
  20429. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20430. * Supports definition of mesh facing forward or backward
  20431. * @param amountRight defines the distance on the right axis
  20432. * @param amountUp defines the distance on the up axis
  20433. * @param amountForward defines the distance on the forward axis
  20434. * @returns the current mesh
  20435. */
  20436. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20437. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20438. return this;
  20439. };
  20440. /**
  20441. * Calculate relative position change from the point of view of behind the front of the mesh.
  20442. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20443. * Supports definition of mesh facing forward or backward
  20444. * @param amountRight defines the distance on the right axis
  20445. * @param amountUp defines the distance on the up axis
  20446. * @param amountForward defines the distance on the forward axis
  20447. * @returns the new displacement vector
  20448. */
  20449. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20450. var rotMatrix = new BABYLON.Matrix();
  20451. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20452. rotQuaternion.toRotationMatrix(rotMatrix);
  20453. var translationDelta = BABYLON.Vector3.Zero();
  20454. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20455. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20456. return translationDelta;
  20457. };
  20458. // ================================== Point of View Rotation =================================
  20459. /**
  20460. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20461. * Supports definition of mesh facing forward or backward
  20462. * @param flipBack defines the flip
  20463. * @param twirlClockwise defines the twirl
  20464. * @param tiltRight defines the tilt
  20465. * @returns the current mesh
  20466. */
  20467. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20468. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20469. return this;
  20470. };
  20471. /**
  20472. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20473. * Supports definition of mesh facing forward or backward.
  20474. * @param flipBack defines the flip
  20475. * @param twirlClockwise defines the twirl
  20476. * @param tiltRight defines the tilt
  20477. * @returns the new rotation vector
  20478. */
  20479. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20480. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20481. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20482. };
  20483. /**
  20484. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20485. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20486. * @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
  20487. * @returns the new bounding vectors
  20488. */
  20489. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20490. if (includeDescendants === void 0) { includeDescendants = true; }
  20491. if (predicate === void 0) { predicate = null; }
  20492. // Ensures that all world matrix will be recomputed.
  20493. this.getScene().incrementRenderId();
  20494. this.computeWorldMatrix(true);
  20495. var min;
  20496. var max;
  20497. var boundingInfo = this.getBoundingInfo();
  20498. if (!this.subMeshes) {
  20499. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20500. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20501. }
  20502. else {
  20503. min = boundingInfo.boundingBox.minimumWorld;
  20504. max = boundingInfo.boundingBox.maximumWorld;
  20505. }
  20506. if (includeDescendants) {
  20507. var descendants = this.getDescendants(false);
  20508. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20509. var descendant = descendants_1[_i];
  20510. var childMesh = descendant;
  20511. childMesh.computeWorldMatrix(true);
  20512. // Filters meshes based on custom predicate function.
  20513. if (predicate && !predicate(childMesh)) {
  20514. continue;
  20515. }
  20516. //make sure we have the needed params to get mix and max
  20517. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20518. continue;
  20519. }
  20520. var childBoundingInfo = childMesh.getBoundingInfo();
  20521. var boundingBox = childBoundingInfo.boundingBox;
  20522. var minBox = boundingBox.minimumWorld;
  20523. var maxBox = boundingBox.maximumWorld;
  20524. BABYLON.Tools.CheckExtends(minBox, min, max);
  20525. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20526. }
  20527. }
  20528. return {
  20529. min: min,
  20530. max: max
  20531. };
  20532. };
  20533. /** @hidden */
  20534. AbstractMesh.prototype._updateBoundingInfo = function () {
  20535. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20536. this._boundingInfo.update(this.worldMatrixFromCache);
  20537. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20538. return this;
  20539. };
  20540. /** @hidden */
  20541. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20542. if (!this.subMeshes) {
  20543. return this;
  20544. }
  20545. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20546. var subMesh = this.subMeshes[subIndex];
  20547. if (!subMesh.IsGlobal) {
  20548. subMesh.updateBoundingInfo(matrix);
  20549. }
  20550. }
  20551. return this;
  20552. };
  20553. /** @hidden */
  20554. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20555. // Bounding info
  20556. this._updateBoundingInfo();
  20557. };
  20558. /**
  20559. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20560. * A mesh is in the frustum if its bounding box intersects the frustum
  20561. * @param frustumPlanes defines the frustum to test
  20562. * @returns true if the mesh is in the frustum planes
  20563. */
  20564. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20565. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20566. };
  20567. /**
  20568. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20569. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20570. * @param frustumPlanes defines the frustum to test
  20571. * @returns true if the mesh is completely in the frustum planes
  20572. */
  20573. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20574. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20575. };
  20576. /**
  20577. * True if the mesh intersects another mesh or a SolidParticle object
  20578. * @param mesh defines a target mesh or SolidParticle to test
  20579. * @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)
  20580. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20581. * @returns true if there is an intersection
  20582. */
  20583. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20584. if (precise === void 0) { precise = false; }
  20585. if (!this._boundingInfo || !mesh._boundingInfo) {
  20586. return false;
  20587. }
  20588. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20589. return true;
  20590. }
  20591. if (includeDescendants) {
  20592. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20593. var child = _a[_i];
  20594. if (child.intersectsMesh(mesh, precise, true)) {
  20595. return true;
  20596. }
  20597. }
  20598. }
  20599. return false;
  20600. };
  20601. /**
  20602. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20603. * @param point defines the point to test
  20604. * @returns true if there is an intersection
  20605. */
  20606. AbstractMesh.prototype.intersectsPoint = function (point) {
  20607. if (!this._boundingInfo) {
  20608. return false;
  20609. }
  20610. return this._boundingInfo.intersectsPoint(point);
  20611. };
  20612. /**
  20613. * Gets the current physics impostor
  20614. * @see http://doc.babylonjs.com/features/physics_engine
  20615. * @returns a physics impostor or null
  20616. */
  20617. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20618. return this.physicsImpostor;
  20619. };
  20620. /**
  20621. * Gets the position of the current mesh in camera space
  20622. * @param camera defines the camera to use
  20623. * @returns a position
  20624. */
  20625. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20626. if (camera === void 0) { camera = null; }
  20627. if (!camera) {
  20628. camera = this.getScene().activeCamera;
  20629. }
  20630. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20631. };
  20632. /**
  20633. * Returns the distance from the mesh to the active camera
  20634. * @param camera defines the camera to use
  20635. * @returns the distance
  20636. */
  20637. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20638. if (camera === void 0) { camera = null; }
  20639. if (!camera) {
  20640. camera = this.getScene().activeCamera;
  20641. }
  20642. return this.absolutePosition.subtract(camera.position).length();
  20643. };
  20644. /**
  20645. * Apply a physic impulse to the mesh
  20646. * @param force defines the force to apply
  20647. * @param contactPoint defines where to apply the force
  20648. * @returns the current mesh
  20649. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20650. */
  20651. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20652. if (!this.physicsImpostor) {
  20653. return this;
  20654. }
  20655. this.physicsImpostor.applyImpulse(force, contactPoint);
  20656. return this;
  20657. };
  20658. /**
  20659. * Creates a physic joint between two meshes
  20660. * @param otherMesh defines the other mesh to use
  20661. * @param pivot1 defines the pivot to use on this mesh
  20662. * @param pivot2 defines the pivot to use on the other mesh
  20663. * @param options defines additional options (can be plugin dependent)
  20664. * @returns the current mesh
  20665. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20666. */
  20667. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20668. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20669. return this;
  20670. }
  20671. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20672. mainPivot: pivot1,
  20673. connectedPivot: pivot2,
  20674. nativeParams: options
  20675. });
  20676. return this;
  20677. };
  20678. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20679. // Collisions
  20680. /**
  20681. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20682. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20683. */
  20684. get: function () {
  20685. return this._checkCollisions;
  20686. },
  20687. set: function (collisionEnabled) {
  20688. this._checkCollisions = collisionEnabled;
  20689. if (this.getScene().workerCollisions) {
  20690. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20691. }
  20692. },
  20693. enumerable: true,
  20694. configurable: true
  20695. });
  20696. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20697. /**
  20698. * Gets Collider object used to compute collisions (not physics)
  20699. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20700. */
  20701. get: function () {
  20702. return this._collider;
  20703. },
  20704. enumerable: true,
  20705. configurable: true
  20706. });
  20707. /**
  20708. * Move the mesh using collision engine
  20709. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20710. * @param displacement defines the requested displacement vector
  20711. * @returns the current mesh
  20712. */
  20713. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20714. var globalPosition = this.getAbsolutePosition();
  20715. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20716. if (!this._collider) {
  20717. this._collider = new BABYLON.Collider();
  20718. }
  20719. this._collider._radius = this.ellipsoid;
  20720. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20721. return this;
  20722. };
  20723. // Submeshes octree
  20724. /**
  20725. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20726. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20727. * @param maxCapacity defines the maximum size of each block (64 by default)
  20728. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20729. * @returns the new octree
  20730. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20731. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20732. */
  20733. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20734. if (maxCapacity === void 0) { maxCapacity = 64; }
  20735. if (maxDepth === void 0) { maxDepth = 2; }
  20736. if (!this._submeshesOctree) {
  20737. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20738. }
  20739. this.computeWorldMatrix(true);
  20740. var boundingInfo = this.getBoundingInfo();
  20741. // Update octree
  20742. var bbox = boundingInfo.boundingBox;
  20743. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20744. return this._submeshesOctree;
  20745. };
  20746. // Collisions
  20747. /** @hidden */
  20748. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20749. this._generatePointsArray();
  20750. if (!this._positions) {
  20751. return this;
  20752. }
  20753. // Transformation
  20754. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20755. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20756. subMesh._lastColliderWorldVertices = [];
  20757. subMesh._trianglePlanes = [];
  20758. var start = subMesh.verticesStart;
  20759. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20760. for (var i = start; i < end; i++) {
  20761. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20762. }
  20763. }
  20764. // Collide
  20765. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20766. if (collider.collisionFound) {
  20767. collider.collidedMesh = this;
  20768. }
  20769. return this;
  20770. };
  20771. /** @hidden */
  20772. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20773. var subMeshes;
  20774. var len;
  20775. // Octrees
  20776. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20777. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20778. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20779. len = intersections.length;
  20780. subMeshes = intersections.data;
  20781. }
  20782. else {
  20783. subMeshes = this.subMeshes;
  20784. len = subMeshes.length;
  20785. }
  20786. for (var index = 0; index < len; index++) {
  20787. var subMesh = subMeshes[index];
  20788. // Bounding test
  20789. if (len > 1 && !subMesh._checkCollision(collider))
  20790. continue;
  20791. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20792. }
  20793. return this;
  20794. };
  20795. /** @hidden */
  20796. AbstractMesh.prototype._checkCollision = function (collider) {
  20797. // Bounding box test
  20798. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20799. return this;
  20800. // Transformation matrix
  20801. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20802. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20803. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20804. return this;
  20805. };
  20806. // Picking
  20807. /** @hidden */
  20808. AbstractMesh.prototype._generatePointsArray = function () {
  20809. return false;
  20810. };
  20811. /**
  20812. * Checks if the passed Ray intersects with the mesh
  20813. * @param ray defines the ray to use
  20814. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20815. * @returns the picking info
  20816. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20817. */
  20818. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20819. var pickingInfo = new BABYLON.PickingInfo();
  20820. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20821. return pickingInfo;
  20822. }
  20823. if (!this._generatePointsArray()) {
  20824. return pickingInfo;
  20825. }
  20826. var intersectInfo = null;
  20827. // Octrees
  20828. var subMeshes;
  20829. var len;
  20830. if (this._submeshesOctree && this.useOctreeForPicking) {
  20831. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20832. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20833. len = intersections.length;
  20834. subMeshes = intersections.data;
  20835. }
  20836. else {
  20837. subMeshes = this.subMeshes;
  20838. len = subMeshes.length;
  20839. }
  20840. for (var index = 0; index < len; index++) {
  20841. var subMesh = subMeshes[index];
  20842. // Bounding test
  20843. if (len > 1 && !subMesh.canIntersects(ray))
  20844. continue;
  20845. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20846. if (currentIntersectInfo) {
  20847. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20848. intersectInfo = currentIntersectInfo;
  20849. intersectInfo.subMeshId = index;
  20850. if (fastCheck) {
  20851. break;
  20852. }
  20853. }
  20854. }
  20855. }
  20856. if (intersectInfo) {
  20857. // Get picked point
  20858. var world = this.getWorldMatrix();
  20859. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20860. var direction = ray.direction.clone();
  20861. direction = direction.scale(intersectInfo.distance);
  20862. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20863. var pickedPoint = worldOrigin.add(worldDirection);
  20864. // Return result
  20865. pickingInfo.hit = true;
  20866. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20867. pickingInfo.pickedPoint = pickedPoint;
  20868. pickingInfo.pickedMesh = this;
  20869. pickingInfo.bu = intersectInfo.bu || 0;
  20870. pickingInfo.bv = intersectInfo.bv || 0;
  20871. pickingInfo.faceId = intersectInfo.faceId;
  20872. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20873. return pickingInfo;
  20874. }
  20875. return pickingInfo;
  20876. };
  20877. /**
  20878. * Clones the current mesh
  20879. * @param name defines the mesh name
  20880. * @param newParent defines the new mesh parent
  20881. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20882. * @returns the new mesh
  20883. */
  20884. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20885. return null;
  20886. };
  20887. /**
  20888. * Disposes all the submeshes of the current meshnp
  20889. * @returns the current mesh
  20890. */
  20891. AbstractMesh.prototype.releaseSubMeshes = function () {
  20892. if (this.subMeshes) {
  20893. while (this.subMeshes.length) {
  20894. this.subMeshes[0].dispose();
  20895. }
  20896. }
  20897. else {
  20898. this.subMeshes = new Array();
  20899. }
  20900. return this;
  20901. };
  20902. /**
  20903. * Releases resources associated with this abstract mesh.
  20904. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20905. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20906. */
  20907. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20908. var _this = this;
  20909. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20910. var index;
  20911. // Smart Array Retainers.
  20912. this.getScene().freeActiveMeshes();
  20913. this.getScene().freeRenderingGroups();
  20914. // Action manager
  20915. if (this.actionManager !== undefined && this.actionManager !== null) {
  20916. this.actionManager.dispose();
  20917. this.actionManager = null;
  20918. }
  20919. // Skeleton
  20920. this._skeleton = null;
  20921. // Physics
  20922. if (this.physicsImpostor) {
  20923. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20924. }
  20925. // Intersections in progress
  20926. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20927. var other = this._intersectionsInProgress[index];
  20928. var pos = other._intersectionsInProgress.indexOf(this);
  20929. other._intersectionsInProgress.splice(pos, 1);
  20930. }
  20931. this._intersectionsInProgress = [];
  20932. // Lights
  20933. var lights = this.getScene().lights;
  20934. lights.forEach(function (light) {
  20935. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20936. if (meshIndex !== -1) {
  20937. light.includedOnlyMeshes.splice(meshIndex, 1);
  20938. }
  20939. meshIndex = light.excludedMeshes.indexOf(_this);
  20940. if (meshIndex !== -1) {
  20941. light.excludedMeshes.splice(meshIndex, 1);
  20942. }
  20943. // Shadow generators
  20944. var generator = light.getShadowGenerator();
  20945. if (generator) {
  20946. var shadowMap = generator.getShadowMap();
  20947. if (shadowMap && shadowMap.renderList) {
  20948. meshIndex = shadowMap.renderList.indexOf(_this);
  20949. if (meshIndex !== -1) {
  20950. shadowMap.renderList.splice(meshIndex, 1);
  20951. }
  20952. }
  20953. }
  20954. });
  20955. // Edges
  20956. if (this._edgesRenderer) {
  20957. this._edgesRenderer.dispose();
  20958. this._edgesRenderer = null;
  20959. }
  20960. // SubMeshes
  20961. if (this.getClassName() !== "InstancedMesh") {
  20962. this.releaseSubMeshes();
  20963. }
  20964. // Octree
  20965. var sceneOctree = this.getScene().selectionOctree;
  20966. if (sceneOctree !== undefined && sceneOctree !== null) {
  20967. var index = sceneOctree.dynamicContent.indexOf(this);
  20968. if (index !== -1) {
  20969. sceneOctree.dynamicContent.splice(index, 1);
  20970. }
  20971. }
  20972. // Query
  20973. var engine = this.getScene().getEngine();
  20974. if (this._occlusionQuery) {
  20975. this._isOcclusionQueryInProgress = false;
  20976. engine.deleteQuery(this._occlusionQuery);
  20977. this._occlusionQuery = null;
  20978. }
  20979. // Engine
  20980. engine.wipeCaches();
  20981. // Remove from scene
  20982. this.getScene().removeMesh(this);
  20983. if (disposeMaterialAndTextures) {
  20984. if (this.material) {
  20985. this.material.dispose(false, true);
  20986. }
  20987. }
  20988. if (!doNotRecurse) {
  20989. // Particles
  20990. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20991. if (this.getScene().particleSystems[index].emitter === this) {
  20992. this.getScene().particleSystems[index].dispose();
  20993. index--;
  20994. }
  20995. }
  20996. }
  20997. // facet data
  20998. if (this._facetDataEnabled) {
  20999. this.disableFacetData();
  21000. }
  21001. this.onAfterWorldMatrixUpdateObservable.clear();
  21002. this.onCollideObservable.clear();
  21003. this.onCollisionPositionChangeObservable.clear();
  21004. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21005. };
  21006. /**
  21007. * Adds the passed mesh as a child to the current mesh
  21008. * @param mesh defines the child mesh
  21009. * @returns the current mesh
  21010. */
  21011. AbstractMesh.prototype.addChild = function (mesh) {
  21012. mesh.setParent(this);
  21013. return this;
  21014. };
  21015. /**
  21016. * Removes the passed mesh from the current mesh children list
  21017. * @param mesh defines the child mesh
  21018. * @returns the current mesh
  21019. */
  21020. AbstractMesh.prototype.removeChild = function (mesh) {
  21021. mesh.setParent(null);
  21022. return this;
  21023. };
  21024. // Facet data
  21025. /** @hidden */
  21026. AbstractMesh.prototype._initFacetData = function () {
  21027. if (!this._facetNormals) {
  21028. this._facetNormals = new Array();
  21029. }
  21030. if (!this._facetPositions) {
  21031. this._facetPositions = new Array();
  21032. }
  21033. if (!this._facetPartitioning) {
  21034. this._facetPartitioning = new Array();
  21035. }
  21036. this._facetNb = (this.getIndices().length / 3) | 0;
  21037. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21038. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21039. for (var f = 0; f < this._facetNb; f++) {
  21040. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21041. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21042. }
  21043. this._facetDataEnabled = true;
  21044. return this;
  21045. };
  21046. /**
  21047. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21048. * This method can be called within the render loop.
  21049. * 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
  21050. * @returns the current mesh
  21051. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21052. */
  21053. AbstractMesh.prototype.updateFacetData = function () {
  21054. if (!this._facetDataEnabled) {
  21055. this._initFacetData();
  21056. }
  21057. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21058. var indices = this.getIndices();
  21059. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21060. var bInfo = this.getBoundingInfo();
  21061. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21062. // init arrays, matrix and sort function on first call
  21063. this._facetDepthSortEnabled = true;
  21064. if (indices instanceof Uint16Array) {
  21065. this._depthSortedIndices = new Uint16Array(indices);
  21066. }
  21067. else if (indices instanceof Uint32Array) {
  21068. this._depthSortedIndices = new Uint32Array(indices);
  21069. }
  21070. else {
  21071. var needs32bits = false;
  21072. for (var i = 0; i < indices.length; i++) {
  21073. if (indices[i] > 65535) {
  21074. needs32bits = true;
  21075. break;
  21076. }
  21077. }
  21078. if (needs32bits) {
  21079. this._depthSortedIndices = new Uint32Array(indices);
  21080. }
  21081. else {
  21082. this._depthSortedIndices = new Uint16Array(indices);
  21083. }
  21084. }
  21085. this._facetDepthSortFunction = function (f1, f2) {
  21086. return (f2.sqDistance - f1.sqDistance);
  21087. };
  21088. if (!this._facetDepthSortFrom) {
  21089. var camera = this.getScene().activeCamera;
  21090. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21091. }
  21092. this._depthSortedFacets = [];
  21093. for (var f = 0; f < this._facetNb; f++) {
  21094. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21095. this._depthSortedFacets.push(depthSortedFacet);
  21096. }
  21097. this._invertedMatrix = BABYLON.Matrix.Identity();
  21098. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21099. }
  21100. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21101. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21102. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21103. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21104. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21105. this._subDiv.max = this._partitioningSubdivisions;
  21106. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21107. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21108. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21109. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21110. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21111. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21112. // set the parameters for ComputeNormals()
  21113. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21114. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21115. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21116. this._facetParameters.bInfo = bInfo;
  21117. this._facetParameters.bbSize = this._bbSize;
  21118. this._facetParameters.subDiv = this._subDiv;
  21119. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21120. this._facetParameters.depthSort = this._facetDepthSort;
  21121. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21122. this.computeWorldMatrix(true);
  21123. this._worldMatrix.invertToRef(this._invertedMatrix);
  21124. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21125. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21126. }
  21127. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21128. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21129. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21130. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21131. var l = (this._depthSortedIndices.length / 3) | 0;
  21132. for (var f = 0; f < l; f++) {
  21133. var sind = this._depthSortedFacets[f].ind;
  21134. this._depthSortedIndices[f * 3] = indices[sind];
  21135. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21136. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21137. }
  21138. this.updateIndices(this._depthSortedIndices);
  21139. }
  21140. return this;
  21141. };
  21142. /**
  21143. * Returns the facetLocalNormals array.
  21144. * The normals are expressed in the mesh local spac
  21145. * @returns an array of Vector3
  21146. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21147. */
  21148. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21149. if (!this._facetNormals) {
  21150. this.updateFacetData();
  21151. }
  21152. return this._facetNormals;
  21153. };
  21154. /**
  21155. * Returns the facetLocalPositions array.
  21156. * The facet positions are expressed in the mesh local space
  21157. * @returns an array of Vector3
  21158. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21159. */
  21160. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21161. if (!this._facetPositions) {
  21162. this.updateFacetData();
  21163. }
  21164. return this._facetPositions;
  21165. };
  21166. /**
  21167. * Returns the facetLocalPartioning array
  21168. * @returns an array of array of numbers
  21169. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21170. */
  21171. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21172. if (!this._facetPartitioning) {
  21173. this.updateFacetData();
  21174. }
  21175. return this._facetPartitioning;
  21176. };
  21177. /**
  21178. * Returns the i-th facet position in the world system.
  21179. * This method allocates a new Vector3 per call
  21180. * @param i defines the facet index
  21181. * @returns a new Vector3
  21182. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21183. */
  21184. AbstractMesh.prototype.getFacetPosition = function (i) {
  21185. var pos = BABYLON.Vector3.Zero();
  21186. this.getFacetPositionToRef(i, pos);
  21187. return pos;
  21188. };
  21189. /**
  21190. * Sets the reference Vector3 with the i-th facet position in the world system
  21191. * @param i defines the facet index
  21192. * @param ref defines the target vector
  21193. * @returns the current mesh
  21194. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21195. */
  21196. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21197. var localPos = (this.getFacetLocalPositions())[i];
  21198. var world = this.getWorldMatrix();
  21199. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21200. return this;
  21201. };
  21202. /**
  21203. * Returns the i-th facet normal in the world system.
  21204. * This method allocates a new Vector3 per call
  21205. * @param i defines the facet index
  21206. * @returns a new Vector3
  21207. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21208. */
  21209. AbstractMesh.prototype.getFacetNormal = function (i) {
  21210. var norm = BABYLON.Vector3.Zero();
  21211. this.getFacetNormalToRef(i, norm);
  21212. return norm;
  21213. };
  21214. /**
  21215. * Sets the reference Vector3 with the i-th facet normal in the world system
  21216. * @param i defines the facet index
  21217. * @param ref defines the target vector
  21218. * @returns the current mesh
  21219. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21220. */
  21221. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21222. var localNorm = (this.getFacetLocalNormals())[i];
  21223. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21224. return this;
  21225. };
  21226. /**
  21227. * 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)
  21228. * @param x defines x coordinate
  21229. * @param y defines y coordinate
  21230. * @param z defines z coordinate
  21231. * @returns the array of facet indexes
  21232. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21233. */
  21234. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21235. var bInfo = this.getBoundingInfo();
  21236. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21237. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21238. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21239. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21240. return null;
  21241. }
  21242. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21243. };
  21244. /**
  21245. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21246. * @param projected sets as the (x,y,z) world projection on the facet
  21247. * @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
  21248. * @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
  21249. * @param x defines x coordinate
  21250. * @param y defines y coordinate
  21251. * @param z defines z coordinate
  21252. * @returns the face index if found (or null instead)
  21253. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21254. */
  21255. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21256. if (checkFace === void 0) { checkFace = false; }
  21257. if (facing === void 0) { facing = true; }
  21258. var world = this.getWorldMatrix();
  21259. var invMat = BABYLON.Tmp.Matrix[5];
  21260. world.invertToRef(invMat);
  21261. var invVect = BABYLON.Tmp.Vector3[8];
  21262. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21263. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21264. if (projected) {
  21265. // tranform the local computed projected vector to world coordinates
  21266. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21267. }
  21268. return closest;
  21269. };
  21270. /**
  21271. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21272. * @param projected sets as the (x,y,z) local projection on the facet
  21273. * @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
  21274. * @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
  21275. * @param x defines x coordinate
  21276. * @param y defines y coordinate
  21277. * @param z defines z coordinate
  21278. * @returns the face index if found (or null instead)
  21279. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21280. */
  21281. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21282. if (checkFace === void 0) { checkFace = false; }
  21283. if (facing === void 0) { facing = true; }
  21284. var closest = null;
  21285. var tmpx = 0.0;
  21286. var tmpy = 0.0;
  21287. var tmpz = 0.0;
  21288. var d = 0.0; // tmp dot facet normal * facet position
  21289. var t0 = 0.0;
  21290. var projx = 0.0;
  21291. var projy = 0.0;
  21292. var projz = 0.0;
  21293. // Get all the facets in the same partitioning block than (x, y, z)
  21294. var facetPositions = this.getFacetLocalPositions();
  21295. var facetNormals = this.getFacetLocalNormals();
  21296. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21297. if (!facetsInBlock) {
  21298. return null;
  21299. }
  21300. // Get the closest facet to (x, y, z)
  21301. var shortest = Number.MAX_VALUE; // init distance vars
  21302. var tmpDistance = shortest;
  21303. var fib; // current facet in the block
  21304. var norm; // current facet normal
  21305. var p0; // current facet barycenter position
  21306. // loop on all the facets in the current partitioning block
  21307. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21308. fib = facetsInBlock[idx];
  21309. norm = facetNormals[fib];
  21310. p0 = facetPositions[fib];
  21311. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21312. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21313. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21314. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21315. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21316. projx = x + norm.x * t0;
  21317. projy = y + norm.y * t0;
  21318. projz = z + norm.z * t0;
  21319. tmpx = projx - x;
  21320. tmpy = projy - y;
  21321. tmpz = projz - z;
  21322. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21323. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21324. shortest = tmpDistance;
  21325. closest = fib;
  21326. if (projected) {
  21327. projected.x = projx;
  21328. projected.y = projy;
  21329. projected.z = projz;
  21330. }
  21331. }
  21332. }
  21333. }
  21334. return closest;
  21335. };
  21336. /**
  21337. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21338. * @returns the parameters
  21339. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21340. */
  21341. AbstractMesh.prototype.getFacetDataParameters = function () {
  21342. return this._facetParameters;
  21343. };
  21344. /**
  21345. * Disables the feature FacetData and frees the related memory
  21346. * @returns the current mesh
  21347. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21348. */
  21349. AbstractMesh.prototype.disableFacetData = function () {
  21350. if (this._facetDataEnabled) {
  21351. this._facetDataEnabled = false;
  21352. this._facetPositions = new Array();
  21353. this._facetNormals = new Array();
  21354. this._facetPartitioning = new Array();
  21355. this._facetParameters = null;
  21356. this._depthSortedIndices = new Uint32Array(0);
  21357. }
  21358. return this;
  21359. };
  21360. /**
  21361. * Updates the AbstractMesh indices array
  21362. * @param indices defines the data source
  21363. * @returns the current mesh
  21364. */
  21365. AbstractMesh.prototype.updateIndices = function (indices) {
  21366. return this;
  21367. };
  21368. /**
  21369. * Creates new normals data for the mesh
  21370. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21371. * @returns the current mesh
  21372. */
  21373. AbstractMesh.prototype.createNormals = function (updatable) {
  21374. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21375. var indices = this.getIndices();
  21376. var normals;
  21377. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21378. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21379. }
  21380. else {
  21381. normals = [];
  21382. }
  21383. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21384. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21385. return this;
  21386. };
  21387. /**
  21388. * Align the mesh with a normal
  21389. * @param normal defines the normal to use
  21390. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21391. * @returns the current mesh
  21392. */
  21393. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21394. if (!upDirection) {
  21395. upDirection = BABYLON.Axis.Y;
  21396. }
  21397. var axisX = BABYLON.Tmp.Vector3[0];
  21398. var axisZ = BABYLON.Tmp.Vector3[1];
  21399. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21400. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21401. if (this.rotationQuaternion) {
  21402. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21403. }
  21404. else {
  21405. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21406. }
  21407. return this;
  21408. };
  21409. /** @hidden */
  21410. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21411. this._isOccluded = false;
  21412. };
  21413. /** No occlusion */
  21414. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21415. /** Occlusion set to optimisitic */
  21416. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21417. /** Occlusion set to strict */
  21418. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21419. /** Use an accurante occlusion algorithm */
  21420. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21421. /** Use a conservative occlusion algorithm */
  21422. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21423. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21424. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21425. /** Culling strategy with bounding sphere only and then frustum culling */
  21426. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21427. return AbstractMesh;
  21428. }(BABYLON.TransformNode));
  21429. BABYLON.AbstractMesh = AbstractMesh;
  21430. })(BABYLON || (BABYLON = {}));
  21431. //# sourceMappingURL=babylon.abstractMesh.js.map
  21432. var BABYLON;
  21433. (function (BABYLON) {
  21434. /**
  21435. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21436. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21437. * 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.
  21438. */
  21439. var Light = /** @class */ (function (_super) {
  21440. __extends(Light, _super);
  21441. /**
  21442. * Creates a Light object in the scene.
  21443. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21444. * @param name The firendly name of the light
  21445. * @param scene The scene the light belongs too
  21446. */
  21447. function Light(name, scene) {
  21448. var _this = _super.call(this, name, scene) || this;
  21449. /**
  21450. * Diffuse gives the basic color to an object.
  21451. */
  21452. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21453. /**
  21454. * Specular produces a highlight color on an object.
  21455. * Note: This is note affecting PBR materials.
  21456. */
  21457. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21458. /**
  21459. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21460. * falling off base on range or angle.
  21461. * This can be set to any values in Light.FALLOFF_x.
  21462. *
  21463. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21464. * other types of materials.
  21465. */
  21466. _this.falloffType = Light.FALLOFF_DEFAULT;
  21467. /**
  21468. * Strength of the light.
  21469. * Note: By default it is define in the framework own unit.
  21470. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21471. */
  21472. _this.intensity = 1.0;
  21473. _this._range = Number.MAX_VALUE;
  21474. _this._inverseSquaredRange = 0;
  21475. /**
  21476. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21477. * of light.
  21478. */
  21479. _this._photometricScale = 1.0;
  21480. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21481. _this._radius = 0.00001;
  21482. /**
  21483. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21484. * exceeding the number allowed of the materials.
  21485. */
  21486. _this.renderPriority = 0;
  21487. _this._shadowEnabled = true;
  21488. _this._excludeWithLayerMask = 0;
  21489. _this._includeOnlyWithLayerMask = 0;
  21490. _this._lightmapMode = 0;
  21491. /**
  21492. * @hidden Internal use only.
  21493. */
  21494. _this._excludedMeshesIds = new Array();
  21495. /**
  21496. * @hidden Internal use only.
  21497. */
  21498. _this._includedOnlyMeshesIds = new Array();
  21499. _this.getScene().addLight(_this);
  21500. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21501. _this._buildUniformLayout();
  21502. _this.includedOnlyMeshes = new Array();
  21503. _this.excludedMeshes = new Array();
  21504. _this._resyncMeshes();
  21505. return _this;
  21506. }
  21507. Object.defineProperty(Light.prototype, "range", {
  21508. /**
  21509. * Defines how far from the source the light is impacting in scene units.
  21510. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21511. */
  21512. get: function () {
  21513. return this._range;
  21514. },
  21515. /**
  21516. * Defines how far from the source the light is impacting in scene units.
  21517. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21518. */
  21519. set: function (value) {
  21520. this._range = value;
  21521. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. Object.defineProperty(Light.prototype, "intensityMode", {
  21527. /**
  21528. * Gets the photometric scale used to interpret the intensity.
  21529. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21530. */
  21531. get: function () {
  21532. return this._intensityMode;
  21533. },
  21534. /**
  21535. * Sets the photometric scale used to interpret the intensity.
  21536. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21537. */
  21538. set: function (value) {
  21539. this._intensityMode = value;
  21540. this._computePhotometricScale();
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. ;
  21546. ;
  21547. Object.defineProperty(Light.prototype, "radius", {
  21548. /**
  21549. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21550. */
  21551. get: function () {
  21552. return this._radius;
  21553. },
  21554. /**
  21555. * sets the light radius used by PBR Materials to simulate soft area lights.
  21556. */
  21557. set: function (value) {
  21558. this._radius = value;
  21559. this._computePhotometricScale();
  21560. },
  21561. enumerable: true,
  21562. configurable: true
  21563. });
  21564. ;
  21565. ;
  21566. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21567. /**
  21568. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21569. * the current shadow generator.
  21570. */
  21571. get: function () {
  21572. return this._shadowEnabled;
  21573. },
  21574. /**
  21575. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21576. * the current shadow generator.
  21577. */
  21578. set: function (value) {
  21579. if (this._shadowEnabled === value) {
  21580. return;
  21581. }
  21582. this._shadowEnabled = value;
  21583. this._markMeshesAsLightDirty();
  21584. },
  21585. enumerable: true,
  21586. configurable: true
  21587. });
  21588. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21589. /**
  21590. * Gets the only meshes impacted by this light.
  21591. */
  21592. get: function () {
  21593. return this._includedOnlyMeshes;
  21594. },
  21595. /**
  21596. * Sets the only meshes impacted by this light.
  21597. */
  21598. set: function (value) {
  21599. this._includedOnlyMeshes = value;
  21600. this._hookArrayForIncludedOnly(value);
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21606. /**
  21607. * Gets the meshes not impacted by this light.
  21608. */
  21609. get: function () {
  21610. return this._excludedMeshes;
  21611. },
  21612. /**
  21613. * Sets the meshes not impacted by this light.
  21614. */
  21615. set: function (value) {
  21616. this._excludedMeshes = value;
  21617. this._hookArrayForExcluded(value);
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21623. /**
  21624. * Gets the layer id use to find what meshes are not impacted by the light.
  21625. * Inactive if 0
  21626. */
  21627. get: function () {
  21628. return this._excludeWithLayerMask;
  21629. },
  21630. /**
  21631. * Sets the layer id use to find what meshes are not impacted by the light.
  21632. * Inactive if 0
  21633. */
  21634. set: function (value) {
  21635. this._excludeWithLayerMask = value;
  21636. this._resyncMeshes();
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21642. /**
  21643. * Gets the layer id use to find what meshes are impacted by the light.
  21644. * Inactive if 0
  21645. */
  21646. get: function () {
  21647. return this._includeOnlyWithLayerMask;
  21648. },
  21649. /**
  21650. * Sets the layer id use to find what meshes are impacted by the light.
  21651. * Inactive if 0
  21652. */
  21653. set: function (value) {
  21654. this._includeOnlyWithLayerMask = value;
  21655. this._resyncMeshes();
  21656. },
  21657. enumerable: true,
  21658. configurable: true
  21659. });
  21660. Object.defineProperty(Light.prototype, "lightmapMode", {
  21661. /**
  21662. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21663. */
  21664. get: function () {
  21665. return this._lightmapMode;
  21666. },
  21667. /**
  21668. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21669. */
  21670. set: function (value) {
  21671. if (this._lightmapMode === value) {
  21672. return;
  21673. }
  21674. this._lightmapMode = value;
  21675. this._markMeshesAsLightDirty();
  21676. },
  21677. enumerable: true,
  21678. configurable: true
  21679. });
  21680. /**
  21681. * Returns the string "Light".
  21682. * @returns the class name
  21683. */
  21684. Light.prototype.getClassName = function () {
  21685. return "Light";
  21686. };
  21687. /**
  21688. * Converts the light information to a readable string for debug purpose.
  21689. * @param fullDetails Supports for multiple levels of logging within scene loading
  21690. * @returns the human readable light info
  21691. */
  21692. Light.prototype.toString = function (fullDetails) {
  21693. var ret = "Name: " + this.name;
  21694. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21695. if (this.animations) {
  21696. for (var i = 0; i < this.animations.length; i++) {
  21697. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21698. }
  21699. }
  21700. if (fullDetails) {
  21701. }
  21702. return ret;
  21703. };
  21704. /**
  21705. * Set the enabled state of this node.
  21706. * @param value - the new enabled state
  21707. */
  21708. Light.prototype.setEnabled = function (value) {
  21709. _super.prototype.setEnabled.call(this, value);
  21710. this._resyncMeshes();
  21711. };
  21712. /**
  21713. * Returns the Light associated shadow generator if any.
  21714. * @return the associated shadow generator.
  21715. */
  21716. Light.prototype.getShadowGenerator = function () {
  21717. return this._shadowGenerator;
  21718. };
  21719. /**
  21720. * Returns a Vector3, the absolute light position in the World.
  21721. * @returns the world space position of the light
  21722. */
  21723. Light.prototype.getAbsolutePosition = function () {
  21724. return BABYLON.Vector3.Zero();
  21725. };
  21726. /**
  21727. * Specifies if the light will affect the passed mesh.
  21728. * @param mesh The mesh to test against the light
  21729. * @return true the mesh is affected otherwise, false.
  21730. */
  21731. Light.prototype.canAffectMesh = function (mesh) {
  21732. if (!mesh) {
  21733. return true;
  21734. }
  21735. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21736. return false;
  21737. }
  21738. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21739. return false;
  21740. }
  21741. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21742. return false;
  21743. }
  21744. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21745. return false;
  21746. }
  21747. return true;
  21748. };
  21749. /**
  21750. * Computes and Returns the light World matrix.
  21751. * @returns the world matrix
  21752. */
  21753. Light.prototype.getWorldMatrix = function () {
  21754. this._currentRenderId = this.getScene().getRenderId();
  21755. this._childRenderId = this._currentRenderId;
  21756. var worldMatrix = this._getWorldMatrix();
  21757. if (this.parent && this.parent.getWorldMatrix) {
  21758. if (!this._parentedWorldMatrix) {
  21759. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21760. }
  21761. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21762. this._markSyncedWithParent();
  21763. return this._parentedWorldMatrix;
  21764. }
  21765. return worldMatrix;
  21766. };
  21767. /**
  21768. * Sort function to order lights for rendering.
  21769. * @param a First Light object to compare to second.
  21770. * @param b Second Light object to compare first.
  21771. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21772. */
  21773. Light.CompareLightsPriority = function (a, b) {
  21774. //shadow-casting lights have priority over non-shadow-casting lights
  21775. //the renderPrioirty is a secondary sort criterion
  21776. if (a.shadowEnabled !== b.shadowEnabled) {
  21777. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21778. }
  21779. return b.renderPriority - a.renderPriority;
  21780. };
  21781. /**
  21782. * Releases resources associated with this node.
  21783. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21784. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21785. */
  21786. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21787. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21788. if (this._shadowGenerator) {
  21789. this._shadowGenerator.dispose();
  21790. this._shadowGenerator = null;
  21791. }
  21792. // Animations
  21793. this.getScene().stopAnimation(this);
  21794. // Remove from meshes
  21795. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21796. var mesh = _a[_i];
  21797. mesh._removeLightSource(this);
  21798. }
  21799. this._uniformBuffer.dispose();
  21800. // Remove from scene
  21801. this.getScene().removeLight(this);
  21802. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21803. };
  21804. /**
  21805. * Returns the light type ID (integer).
  21806. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21807. */
  21808. Light.prototype.getTypeID = function () {
  21809. return 0;
  21810. };
  21811. /**
  21812. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21813. * @returns the scaled intensity in intensity mode unit
  21814. */
  21815. Light.prototype.getScaledIntensity = function () {
  21816. return this._photometricScale * this.intensity;
  21817. };
  21818. /**
  21819. * Returns a new Light object, named "name", from the current one.
  21820. * @param name The name of the cloned light
  21821. * @returns the new created light
  21822. */
  21823. Light.prototype.clone = function (name) {
  21824. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21825. if (!constructor) {
  21826. return null;
  21827. }
  21828. return BABYLON.SerializationHelper.Clone(constructor, this);
  21829. };
  21830. /**
  21831. * Serializes the current light into a Serialization object.
  21832. * @returns the serialized object.
  21833. */
  21834. Light.prototype.serialize = function () {
  21835. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21836. // Type
  21837. serializationObject.type = this.getTypeID();
  21838. // Parent
  21839. if (this.parent) {
  21840. serializationObject.parentId = this.parent.id;
  21841. }
  21842. // Inclusion / exclusions
  21843. if (this.excludedMeshes.length > 0) {
  21844. serializationObject.excludedMeshesIds = [];
  21845. this.excludedMeshes.forEach(function (mesh) {
  21846. serializationObject.excludedMeshesIds.push(mesh.id);
  21847. });
  21848. }
  21849. if (this.includedOnlyMeshes.length > 0) {
  21850. serializationObject.includedOnlyMeshesIds = [];
  21851. this.includedOnlyMeshes.forEach(function (mesh) {
  21852. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21853. });
  21854. }
  21855. // Animations
  21856. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21857. serializationObject.ranges = this.serializeAnimationRanges();
  21858. return serializationObject;
  21859. };
  21860. /**
  21861. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21862. * This new light is named "name" and added to the passed scene.
  21863. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21864. * @param name The friendly name of the light
  21865. * @param scene The scene the new light will belong to
  21866. * @returns the constructor function
  21867. */
  21868. Light.GetConstructorFromName = function (type, name, scene) {
  21869. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21870. if (constructorFunc) {
  21871. return constructorFunc;
  21872. }
  21873. // Default to no light for none present once.
  21874. return null;
  21875. };
  21876. /**
  21877. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21878. * @param parsedLight The JSON representation of the light
  21879. * @param scene The scene to create the parsed light in
  21880. * @returns the created light after parsing
  21881. */
  21882. Light.Parse = function (parsedLight, scene) {
  21883. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21884. if (!constructor) {
  21885. return null;
  21886. }
  21887. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21888. // Inclusion / exclusions
  21889. if (parsedLight.excludedMeshesIds) {
  21890. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21891. }
  21892. if (parsedLight.includedOnlyMeshesIds) {
  21893. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21894. }
  21895. // Parent
  21896. if (parsedLight.parentId) {
  21897. light._waitingParentId = parsedLight.parentId;
  21898. }
  21899. // Animations
  21900. if (parsedLight.animations) {
  21901. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21902. var parsedAnimation = parsedLight.animations[animationIndex];
  21903. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21904. }
  21905. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21906. }
  21907. if (parsedLight.autoAnimate) {
  21908. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21909. }
  21910. return light;
  21911. };
  21912. Light.prototype._hookArrayForExcluded = function (array) {
  21913. var _this = this;
  21914. var oldPush = array.push;
  21915. array.push = function () {
  21916. var items = [];
  21917. for (var _i = 0; _i < arguments.length; _i++) {
  21918. items[_i] = arguments[_i];
  21919. }
  21920. var result = oldPush.apply(array, items);
  21921. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21922. var item = items_1[_a];
  21923. item._resyncLighSource(_this);
  21924. }
  21925. return result;
  21926. };
  21927. var oldSplice = array.splice;
  21928. array.splice = function (index, deleteCount) {
  21929. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21930. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21931. var item = deleted_1[_i];
  21932. item._resyncLighSource(_this);
  21933. }
  21934. return deleted;
  21935. };
  21936. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21937. var item = array_1[_i];
  21938. item._resyncLighSource(this);
  21939. }
  21940. };
  21941. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21942. var _this = this;
  21943. var oldPush = array.push;
  21944. array.push = function () {
  21945. var items = [];
  21946. for (var _i = 0; _i < arguments.length; _i++) {
  21947. items[_i] = arguments[_i];
  21948. }
  21949. var result = oldPush.apply(array, items);
  21950. _this._resyncMeshes();
  21951. return result;
  21952. };
  21953. var oldSplice = array.splice;
  21954. array.splice = function (index, deleteCount) {
  21955. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21956. _this._resyncMeshes();
  21957. return deleted;
  21958. };
  21959. this._resyncMeshes();
  21960. };
  21961. Light.prototype._resyncMeshes = function () {
  21962. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21963. var mesh = _a[_i];
  21964. mesh._resyncLighSource(this);
  21965. }
  21966. };
  21967. /**
  21968. * Forces the meshes to update their light related information in their rendering used effects
  21969. * @hidden Internal Use Only
  21970. */
  21971. Light.prototype._markMeshesAsLightDirty = function () {
  21972. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21973. var mesh = _a[_i];
  21974. if (mesh._lightSources.indexOf(this) !== -1) {
  21975. mesh._markSubMeshesAsLightDirty();
  21976. }
  21977. }
  21978. };
  21979. /**
  21980. * Recomputes the cached photometric scale if needed.
  21981. */
  21982. Light.prototype._computePhotometricScale = function () {
  21983. this._photometricScale = this._getPhotometricScale();
  21984. this.getScene().resetCachedMaterial();
  21985. };
  21986. /**
  21987. * Returns the Photometric Scale according to the light type and intensity mode.
  21988. */
  21989. Light.prototype._getPhotometricScale = function () {
  21990. var photometricScale = 0.0;
  21991. var lightTypeID = this.getTypeID();
  21992. //get photometric mode
  21993. var photometricMode = this.intensityMode;
  21994. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21995. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21996. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21997. }
  21998. else {
  21999. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22000. }
  22001. }
  22002. //compute photometric scale
  22003. switch (lightTypeID) {
  22004. case Light.LIGHTTYPEID_POINTLIGHT:
  22005. case Light.LIGHTTYPEID_SPOTLIGHT:
  22006. switch (photometricMode) {
  22007. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22008. photometricScale = 1.0 / (4.0 * Math.PI);
  22009. break;
  22010. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22011. photometricScale = 1.0;
  22012. break;
  22013. case Light.INTENSITYMODE_LUMINANCE:
  22014. photometricScale = this.radius * this.radius;
  22015. break;
  22016. }
  22017. break;
  22018. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22019. switch (photometricMode) {
  22020. case Light.INTENSITYMODE_ILLUMINANCE:
  22021. photometricScale = 1.0;
  22022. break;
  22023. case Light.INTENSITYMODE_LUMINANCE:
  22024. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22025. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22026. var apexAngleRadians = this.radius;
  22027. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22028. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22029. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22030. photometricScale = solidAngle;
  22031. break;
  22032. }
  22033. break;
  22034. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22035. // No fall off in hemisperic light.
  22036. photometricScale = 1.0;
  22037. break;
  22038. }
  22039. return photometricScale;
  22040. };
  22041. /**
  22042. * Reorder the light in the scene according to their defined priority.
  22043. * @hidden Internal Use Only
  22044. */
  22045. Light.prototype._reorderLightsInScene = function () {
  22046. var scene = this.getScene();
  22047. if (this._renderPriority != 0) {
  22048. scene.requireLightSorting = true;
  22049. }
  22050. this.getScene().sortLightsByPriority();
  22051. };
  22052. /**
  22053. * Falloff Default: light is falling off following the material specification:
  22054. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22055. */
  22056. Light.FALLOFF_DEFAULT = 0;
  22057. /**
  22058. * Falloff Physical: light is falling off following the inverse squared distance law.
  22059. */
  22060. Light.FALLOFF_PHYSICAL = 1;
  22061. /**
  22062. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22063. * to enhance interoperability with other engines.
  22064. */
  22065. Light.FALLOFF_GLTF = 2;
  22066. /**
  22067. * Falloff Standard: light is falling off like in the standard material
  22068. * to enhance interoperability with other materials.
  22069. */
  22070. Light.FALLOFF_STANDARD = 3;
  22071. //lightmapMode Consts
  22072. /**
  22073. * If every light affecting the material is in this lightmapMode,
  22074. * material.lightmapTexture adds or multiplies
  22075. * (depends on material.useLightmapAsShadowmap)
  22076. * after every other light calculations.
  22077. */
  22078. Light.LIGHTMAP_DEFAULT = 0;
  22079. /**
  22080. * material.lightmapTexture as only diffuse lighting from this light
  22081. * adds only specular lighting from this light
  22082. * adds dynamic shadows
  22083. */
  22084. Light.LIGHTMAP_SPECULAR = 1;
  22085. /**
  22086. * material.lightmapTexture as only lighting
  22087. * no light calculation from this light
  22088. * only adds dynamic shadows from this light
  22089. */
  22090. Light.LIGHTMAP_SHADOWSONLY = 2;
  22091. // Intensity Mode Consts
  22092. /**
  22093. * Each light type uses the default quantity according to its type:
  22094. * point/spot lights use luminous intensity
  22095. * directional lights use illuminance
  22096. */
  22097. Light.INTENSITYMODE_AUTOMATIC = 0;
  22098. /**
  22099. * lumen (lm)
  22100. */
  22101. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22102. /**
  22103. * candela (lm/sr)
  22104. */
  22105. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22106. /**
  22107. * lux (lm/m^2)
  22108. */
  22109. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22110. /**
  22111. * nit (cd/m^2)
  22112. */
  22113. Light.INTENSITYMODE_LUMINANCE = 4;
  22114. // Light types ids const.
  22115. /**
  22116. * Light type const id of the point light.
  22117. */
  22118. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22119. /**
  22120. * Light type const id of the directional light.
  22121. */
  22122. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22123. /**
  22124. * Light type const id of the spot light.
  22125. */
  22126. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22127. /**
  22128. * Light type const id of the hemispheric light.
  22129. */
  22130. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22131. __decorate([
  22132. BABYLON.serializeAsColor3()
  22133. ], Light.prototype, "diffuse", void 0);
  22134. __decorate([
  22135. BABYLON.serializeAsColor3()
  22136. ], Light.prototype, "specular", void 0);
  22137. __decorate([
  22138. BABYLON.serialize()
  22139. ], Light.prototype, "falloffType", void 0);
  22140. __decorate([
  22141. BABYLON.serialize()
  22142. ], Light.prototype, "intensity", void 0);
  22143. __decorate([
  22144. BABYLON.serialize()
  22145. ], Light.prototype, "range", null);
  22146. __decorate([
  22147. BABYLON.serialize()
  22148. ], Light.prototype, "intensityMode", null);
  22149. __decorate([
  22150. BABYLON.serialize()
  22151. ], Light.prototype, "radius", null);
  22152. __decorate([
  22153. BABYLON.serialize()
  22154. ], Light.prototype, "_renderPriority", void 0);
  22155. __decorate([
  22156. BABYLON.expandToProperty("_reorderLightsInScene")
  22157. ], Light.prototype, "renderPriority", void 0);
  22158. __decorate([
  22159. BABYLON.serialize("shadowEnabled")
  22160. ], Light.prototype, "_shadowEnabled", void 0);
  22161. __decorate([
  22162. BABYLON.serialize("excludeWithLayerMask")
  22163. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22164. __decorate([
  22165. BABYLON.serialize("includeOnlyWithLayerMask")
  22166. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22167. __decorate([
  22168. BABYLON.serialize("lightmapMode")
  22169. ], Light.prototype, "_lightmapMode", void 0);
  22170. return Light;
  22171. }(BABYLON.Node));
  22172. BABYLON.Light = Light;
  22173. })(BABYLON || (BABYLON = {}));
  22174. //# sourceMappingURL=babylon.light.js.map
  22175. var BABYLON;
  22176. (function (BABYLON) {
  22177. var Camera = /** @class */ (function (_super) {
  22178. __extends(Camera, _super);
  22179. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22180. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22181. var _this = _super.call(this, name, scene) || this;
  22182. /**
  22183. * The vector the camera should consider as up.
  22184. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22185. */
  22186. _this.upVector = BABYLON.Vector3.Up();
  22187. _this.orthoLeft = null;
  22188. _this.orthoRight = null;
  22189. _this.orthoBottom = null;
  22190. _this.orthoTop = null;
  22191. /**
  22192. * FOV is set in Radians. (default is 0.8)
  22193. */
  22194. _this.fov = 0.8;
  22195. _this.minZ = 1;
  22196. _this.maxZ = 10000.0;
  22197. _this.inertia = 0.9;
  22198. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22199. _this.isIntermediate = false;
  22200. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22201. /**
  22202. * Restricts the camera to viewing objects with the same layerMask.
  22203. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22204. */
  22205. _this.layerMask = 0x0FFFFFFF;
  22206. /**
  22207. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22208. */
  22209. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22210. // Camera rig members
  22211. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22212. /** @hidden */
  22213. _this._rigCameras = new Array();
  22214. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22215. /** @hidden */
  22216. _this._skipRendering = false;
  22217. _this.customRenderTargets = new Array();
  22218. // Observables
  22219. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22220. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22221. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22222. _this.onRestoreStateObservable = new BABYLON.Observable();
  22223. // Cache
  22224. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22225. _this._projectionMatrix = new BABYLON.Matrix();
  22226. _this._doNotComputeProjectionMatrix = false;
  22227. _this._worldMatrix = BABYLON.Matrix.Identity();
  22228. _this._postProcesses = new Array();
  22229. _this._transformMatrix = BABYLON.Matrix.Zero();
  22230. _this._activeMeshes = new BABYLON.SmartArray(256);
  22231. _this._globalPosition = BABYLON.Vector3.Zero();
  22232. _this._refreshFrustumPlanes = true;
  22233. _this.getScene().addCamera(_this);
  22234. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22235. _this.getScene().activeCamera = _this;
  22236. }
  22237. _this.position = position;
  22238. return _this;
  22239. }
  22240. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22241. get: function () {
  22242. return Camera._PERSPECTIVE_CAMERA;
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22248. get: function () {
  22249. return Camera._ORTHOGRAPHIC_CAMERA;
  22250. },
  22251. enumerable: true,
  22252. configurable: true
  22253. });
  22254. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22255. /**
  22256. * This is the default FOV mode for perspective cameras.
  22257. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22258. *
  22259. */
  22260. get: function () {
  22261. return Camera._FOVMODE_VERTICAL_FIXED;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22267. /**
  22268. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22269. *
  22270. */
  22271. get: function () {
  22272. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22278. get: function () {
  22279. return Camera._RIG_MODE_NONE;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22285. get: function () {
  22286. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22292. get: function () {
  22293. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22294. },
  22295. enumerable: true,
  22296. configurable: true
  22297. });
  22298. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22299. get: function () {
  22300. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22301. },
  22302. enumerable: true,
  22303. configurable: true
  22304. });
  22305. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22306. get: function () {
  22307. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22308. },
  22309. enumerable: true,
  22310. configurable: true
  22311. });
  22312. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22313. get: function () {
  22314. return Camera._RIG_MODE_VR;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22320. get: function () {
  22321. return Camera._RIG_MODE_WEBVR;
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. /**
  22327. * Store current camera state (fov, position, etc..)
  22328. */
  22329. Camera.prototype.storeState = function () {
  22330. this._stateStored = true;
  22331. this._storedFov = this.fov;
  22332. return this;
  22333. };
  22334. /**
  22335. * Restores the camera state values if it has been stored. You must call storeState() first
  22336. */
  22337. Camera.prototype._restoreStateValues = function () {
  22338. if (!this._stateStored) {
  22339. return false;
  22340. }
  22341. this.fov = this._storedFov;
  22342. return true;
  22343. };
  22344. /**
  22345. * Restored camera state. You must call storeState() first
  22346. */
  22347. Camera.prototype.restoreState = function () {
  22348. if (this._restoreStateValues()) {
  22349. this.onRestoreStateObservable.notifyObservers(this);
  22350. return true;
  22351. }
  22352. return false;
  22353. };
  22354. Camera.prototype.getClassName = function () {
  22355. return "Camera";
  22356. };
  22357. /**
  22358. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22359. */
  22360. Camera.prototype.toString = function (fullDetails) {
  22361. var ret = "Name: " + this.name;
  22362. ret += ", type: " + this.getClassName();
  22363. if (this.animations) {
  22364. for (var i = 0; i < this.animations.length; i++) {
  22365. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22366. }
  22367. }
  22368. if (fullDetails) {
  22369. }
  22370. return ret;
  22371. };
  22372. Object.defineProperty(Camera.prototype, "globalPosition", {
  22373. get: function () {
  22374. return this._globalPosition;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Camera.prototype.getActiveMeshes = function () {
  22380. return this._activeMeshes;
  22381. };
  22382. Camera.prototype.isActiveMesh = function (mesh) {
  22383. return (this._activeMeshes.indexOf(mesh) !== -1);
  22384. };
  22385. /**
  22386. * Is this camera ready to be used/rendered
  22387. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22388. * @return true if the camera is ready
  22389. */
  22390. Camera.prototype.isReady = function (completeCheck) {
  22391. if (completeCheck === void 0) { completeCheck = false; }
  22392. if (completeCheck) {
  22393. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22394. var pp = _a[_i];
  22395. if (pp && !pp.isReady()) {
  22396. return false;
  22397. }
  22398. }
  22399. }
  22400. return _super.prototype.isReady.call(this, completeCheck);
  22401. };
  22402. //Cache
  22403. /** @hidden */
  22404. Camera.prototype._initCache = function () {
  22405. _super.prototype._initCache.call(this);
  22406. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22407. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22408. this._cache.mode = undefined;
  22409. this._cache.minZ = undefined;
  22410. this._cache.maxZ = undefined;
  22411. this._cache.fov = undefined;
  22412. this._cache.fovMode = undefined;
  22413. this._cache.aspectRatio = undefined;
  22414. this._cache.orthoLeft = undefined;
  22415. this._cache.orthoRight = undefined;
  22416. this._cache.orthoBottom = undefined;
  22417. this._cache.orthoTop = undefined;
  22418. this._cache.renderWidth = undefined;
  22419. this._cache.renderHeight = undefined;
  22420. };
  22421. /** @hidden */
  22422. Camera.prototype._updateCache = function (ignoreParentClass) {
  22423. if (!ignoreParentClass) {
  22424. _super.prototype._updateCache.call(this);
  22425. }
  22426. this._cache.position.copyFrom(this.position);
  22427. this._cache.upVector.copyFrom(this.upVector);
  22428. };
  22429. // Synchronized
  22430. /** @hidden */
  22431. Camera.prototype._isSynchronized = function () {
  22432. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22433. };
  22434. /** @hidden */
  22435. Camera.prototype._isSynchronizedViewMatrix = function () {
  22436. if (!_super.prototype._isSynchronized.call(this))
  22437. return false;
  22438. return this._cache.position.equals(this.position)
  22439. && this._cache.upVector.equals(this.upVector)
  22440. && this.isSynchronizedWithParent();
  22441. };
  22442. /** @hidden */
  22443. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22444. var check = this._cache.mode === this.mode
  22445. && this._cache.minZ === this.minZ
  22446. && this._cache.maxZ === this.maxZ;
  22447. if (!check) {
  22448. return false;
  22449. }
  22450. var engine = this.getEngine();
  22451. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22452. check = this._cache.fov === this.fov
  22453. && this._cache.fovMode === this.fovMode
  22454. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22455. }
  22456. else {
  22457. check = this._cache.orthoLeft === this.orthoLeft
  22458. && this._cache.orthoRight === this.orthoRight
  22459. && this._cache.orthoBottom === this.orthoBottom
  22460. && this._cache.orthoTop === this.orthoTop
  22461. && this._cache.renderWidth === engine.getRenderWidth()
  22462. && this._cache.renderHeight === engine.getRenderHeight();
  22463. }
  22464. return check;
  22465. };
  22466. // Controls
  22467. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22468. };
  22469. Camera.prototype.detachControl = function (element) {
  22470. };
  22471. Camera.prototype.update = function () {
  22472. this._checkInputs();
  22473. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22474. this._updateRigCameras();
  22475. }
  22476. };
  22477. /** @hidden */
  22478. Camera.prototype._checkInputs = function () {
  22479. this.onAfterCheckInputsObservable.notifyObservers(this);
  22480. };
  22481. Object.defineProperty(Camera.prototype, "rigCameras", {
  22482. get: function () {
  22483. return this._rigCameras;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22489. get: function () {
  22490. return this._rigPostProcess;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. /**
  22496. * Internal, gets the first post proces.
  22497. * @returns the first post process to be run on this camera.
  22498. */
  22499. Camera.prototype._getFirstPostProcess = function () {
  22500. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22501. if (this._postProcesses[ppIndex] !== null) {
  22502. return this._postProcesses[ppIndex];
  22503. }
  22504. }
  22505. return null;
  22506. };
  22507. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22508. // invalidate framebuffer
  22509. var firstPostProcess = this._getFirstPostProcess();
  22510. if (firstPostProcess) {
  22511. firstPostProcess.markTextureDirty();
  22512. }
  22513. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22514. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22515. var cam = this._rigCameras[i];
  22516. var rigPostProcess = cam._rigPostProcess;
  22517. // for VR rig, there does not have to be a post process
  22518. if (rigPostProcess) {
  22519. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22520. if (isPass) {
  22521. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22522. cam.isIntermediate = this._postProcesses.length === 0;
  22523. }
  22524. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22525. rigPostProcess.markTextureDirty();
  22526. }
  22527. else {
  22528. cam._postProcesses = this._postProcesses.slice(0);
  22529. }
  22530. }
  22531. };
  22532. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22533. if (insertAt === void 0) { insertAt = null; }
  22534. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22535. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22536. return 0;
  22537. }
  22538. if (insertAt == null || insertAt < 0) {
  22539. this._postProcesses.push(postProcess);
  22540. }
  22541. else if (this._postProcesses[insertAt] === null) {
  22542. this._postProcesses[insertAt] = postProcess;
  22543. }
  22544. else {
  22545. this._postProcesses.splice(insertAt, 0, postProcess);
  22546. }
  22547. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22548. return this._postProcesses.indexOf(postProcess);
  22549. };
  22550. Camera.prototype.detachPostProcess = function (postProcess) {
  22551. var idx = this._postProcesses.indexOf(postProcess);
  22552. if (idx !== -1) {
  22553. this._postProcesses[idx] = null;
  22554. }
  22555. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22556. };
  22557. Camera.prototype.getWorldMatrix = function () {
  22558. if (this._isSynchronizedViewMatrix()) {
  22559. return this._worldMatrix;
  22560. }
  22561. // Getting the the view matrix will also compute the world matrix.
  22562. this.getViewMatrix();
  22563. return this._worldMatrix;
  22564. };
  22565. /** @hidden */
  22566. Camera.prototype._getViewMatrix = function () {
  22567. return BABYLON.Matrix.Identity();
  22568. };
  22569. Camera.prototype.getViewMatrix = function (force) {
  22570. if (!force && this._isSynchronizedViewMatrix()) {
  22571. return this._computedViewMatrix;
  22572. }
  22573. this.updateCache();
  22574. this._computedViewMatrix = this._getViewMatrix();
  22575. this._currentRenderId = this.getScene().getRenderId();
  22576. this._childRenderId = this._currentRenderId;
  22577. this._refreshFrustumPlanes = true;
  22578. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22579. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22580. }
  22581. this.onViewMatrixChangedObservable.notifyObservers(this);
  22582. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22583. return this._computedViewMatrix;
  22584. };
  22585. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22586. this._doNotComputeProjectionMatrix = true;
  22587. if (projection !== undefined) {
  22588. this._projectionMatrix = projection;
  22589. }
  22590. };
  22591. ;
  22592. Camera.prototype.unfreezeProjectionMatrix = function () {
  22593. this._doNotComputeProjectionMatrix = false;
  22594. };
  22595. ;
  22596. Camera.prototype.getProjectionMatrix = function (force) {
  22597. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22598. return this._projectionMatrix;
  22599. }
  22600. // Cache
  22601. this._cache.mode = this.mode;
  22602. this._cache.minZ = this.minZ;
  22603. this._cache.maxZ = this.maxZ;
  22604. // Matrix
  22605. this._refreshFrustumPlanes = true;
  22606. var engine = this.getEngine();
  22607. var scene = this.getScene();
  22608. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22609. this._cache.fov = this.fov;
  22610. this._cache.fovMode = this.fovMode;
  22611. this._cache.aspectRatio = engine.getAspectRatio(this);
  22612. if (this.minZ <= 0) {
  22613. this.minZ = 0.1;
  22614. }
  22615. if (scene.useRightHandedSystem) {
  22616. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22617. }
  22618. else {
  22619. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22620. }
  22621. }
  22622. else {
  22623. var halfWidth = engine.getRenderWidth() / 2.0;
  22624. var halfHeight = engine.getRenderHeight() / 2.0;
  22625. if (scene.useRightHandedSystem) {
  22626. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22627. }
  22628. else {
  22629. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22630. }
  22631. this._cache.orthoLeft = this.orthoLeft;
  22632. this._cache.orthoRight = this.orthoRight;
  22633. this._cache.orthoBottom = this.orthoBottom;
  22634. this._cache.orthoTop = this.orthoTop;
  22635. this._cache.renderWidth = engine.getRenderWidth();
  22636. this._cache.renderHeight = engine.getRenderHeight();
  22637. }
  22638. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22639. return this._projectionMatrix;
  22640. };
  22641. /**
  22642. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22643. * @returns a Matrix
  22644. */
  22645. Camera.prototype.getTransformationMatrix = function () {
  22646. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22647. return this._transformMatrix;
  22648. };
  22649. Camera.prototype.updateFrustumPlanes = function () {
  22650. if (!this._refreshFrustumPlanes) {
  22651. return;
  22652. }
  22653. this.getTransformationMatrix();
  22654. if (!this._frustumPlanes) {
  22655. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22656. }
  22657. else {
  22658. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22659. }
  22660. this._refreshFrustumPlanes = false;
  22661. };
  22662. Camera.prototype.isInFrustum = function (target) {
  22663. this.updateFrustumPlanes();
  22664. return target.isInFrustum(this._frustumPlanes);
  22665. };
  22666. Camera.prototype.isCompletelyInFrustum = function (target) {
  22667. this.updateFrustumPlanes();
  22668. return target.isCompletelyInFrustum(this._frustumPlanes);
  22669. };
  22670. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22671. if (length === void 0) { length = 100; }
  22672. if (!transform) {
  22673. transform = this.getWorldMatrix();
  22674. }
  22675. if (!origin) {
  22676. origin = this.position;
  22677. }
  22678. var forward = new BABYLON.Vector3(0, 0, 1);
  22679. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22680. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22681. return new BABYLON.Ray(origin, direction, length);
  22682. };
  22683. /**
  22684. * Releases resources associated with this node.
  22685. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22686. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22687. */
  22688. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22689. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22690. // Observables
  22691. this.onViewMatrixChangedObservable.clear();
  22692. this.onProjectionMatrixChangedObservable.clear();
  22693. this.onAfterCheckInputsObservable.clear();
  22694. this.onRestoreStateObservable.clear();
  22695. // Inputs
  22696. if (this.inputs) {
  22697. this.inputs.clear();
  22698. }
  22699. // Animations
  22700. this.getScene().stopAnimation(this);
  22701. // Remove from scene
  22702. this.getScene().removeCamera(this);
  22703. while (this._rigCameras.length > 0) {
  22704. var camera = this._rigCameras.pop();
  22705. if (camera) {
  22706. camera.dispose();
  22707. }
  22708. }
  22709. // Postprocesses
  22710. if (this._rigPostProcess) {
  22711. this._rigPostProcess.dispose(this);
  22712. this._rigPostProcess = null;
  22713. this._postProcesses = [];
  22714. }
  22715. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22716. this._rigPostProcess = null;
  22717. this._postProcesses = [];
  22718. }
  22719. else {
  22720. var i = this._postProcesses.length;
  22721. while (--i >= 0) {
  22722. var postProcess = this._postProcesses[i];
  22723. if (postProcess) {
  22724. postProcess.dispose(this);
  22725. }
  22726. }
  22727. }
  22728. // Render targets
  22729. var i = this.customRenderTargets.length;
  22730. while (--i >= 0) {
  22731. this.customRenderTargets[i].dispose();
  22732. }
  22733. this.customRenderTargets = [];
  22734. // Active Meshes
  22735. this._activeMeshes.dispose();
  22736. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22737. };
  22738. Object.defineProperty(Camera.prototype, "leftCamera", {
  22739. // ---- Camera rigs section ----
  22740. get: function () {
  22741. if (this._rigCameras.length < 1) {
  22742. return null;
  22743. }
  22744. return this._rigCameras[0];
  22745. },
  22746. enumerable: true,
  22747. configurable: true
  22748. });
  22749. Object.defineProperty(Camera.prototype, "rightCamera", {
  22750. get: function () {
  22751. if (this._rigCameras.length < 2) {
  22752. return null;
  22753. }
  22754. return this._rigCameras[1];
  22755. },
  22756. enumerable: true,
  22757. configurable: true
  22758. });
  22759. Camera.prototype.getLeftTarget = function () {
  22760. if (this._rigCameras.length < 1) {
  22761. return null;
  22762. }
  22763. return this._rigCameras[0].getTarget();
  22764. };
  22765. Camera.prototype.getRightTarget = function () {
  22766. if (this._rigCameras.length < 2) {
  22767. return null;
  22768. }
  22769. return this._rigCameras[1].getTarget();
  22770. };
  22771. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22772. if (this.cameraRigMode === mode) {
  22773. return;
  22774. }
  22775. while (this._rigCameras.length > 0) {
  22776. var camera = this._rigCameras.pop();
  22777. if (camera) {
  22778. camera.dispose();
  22779. }
  22780. }
  22781. this.cameraRigMode = mode;
  22782. this._cameraRigParams = {};
  22783. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22784. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22785. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22786. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22787. // create the rig cameras, unless none
  22788. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22789. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22790. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22791. if (leftCamera && rightCamera) {
  22792. this._rigCameras.push(leftCamera);
  22793. this._rigCameras.push(rightCamera);
  22794. }
  22795. }
  22796. switch (this.cameraRigMode) {
  22797. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22798. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22799. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22800. break;
  22801. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22802. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22803. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22804. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22805. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22806. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22807. break;
  22808. case Camera.RIG_MODE_VR:
  22809. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22810. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22811. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22812. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22813. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22814. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22815. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22816. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22817. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22818. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22819. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22820. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22821. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22822. if (metrics.compensateDistortion) {
  22823. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22824. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22825. }
  22826. break;
  22827. case Camera.RIG_MODE_WEBVR:
  22828. if (rigParams.vrDisplay) {
  22829. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22830. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22831. //Left eye
  22832. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22833. this._rigCameras[0].setCameraRigParameter("left", true);
  22834. //leaving this for future reference
  22835. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22836. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22837. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22838. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22839. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22840. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22841. this._rigCameras[0].parent = this;
  22842. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22843. //Right eye
  22844. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22845. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22846. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22847. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22848. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22849. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22850. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22851. this._rigCameras[1].parent = this;
  22852. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22853. if (Camera.UseAlternateWebVRRendering) {
  22854. this._rigCameras[1]._skipRendering = true;
  22855. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22856. }
  22857. }
  22858. break;
  22859. }
  22860. this._cascadePostProcessesToRigCams();
  22861. this.update();
  22862. };
  22863. Camera.prototype._getVRProjectionMatrix = function () {
  22864. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22865. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22866. return this._projectionMatrix;
  22867. };
  22868. Camera.prototype._updateCameraRotationMatrix = function () {
  22869. //Here for WebVR
  22870. };
  22871. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22872. //Here for WebVR
  22873. };
  22874. /**
  22875. * This function MUST be overwritten by the different WebVR cameras available.
  22876. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22877. */
  22878. Camera.prototype._getWebVRProjectionMatrix = function () {
  22879. return BABYLON.Matrix.Identity();
  22880. };
  22881. /**
  22882. * This function MUST be overwritten by the different WebVR cameras available.
  22883. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22884. */
  22885. Camera.prototype._getWebVRViewMatrix = function () {
  22886. return BABYLON.Matrix.Identity();
  22887. };
  22888. Camera.prototype.setCameraRigParameter = function (name, value) {
  22889. if (!this._cameraRigParams) {
  22890. this._cameraRigParams = {};
  22891. }
  22892. this._cameraRigParams[name] = value;
  22893. //provisionnally:
  22894. if (name === "interaxialDistance") {
  22895. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22896. }
  22897. };
  22898. /**
  22899. * needs to be overridden by children so sub has required properties to be copied
  22900. */
  22901. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22902. return null;
  22903. };
  22904. /**
  22905. * May need to be overridden by children
  22906. * @hidden
  22907. */
  22908. Camera.prototype._updateRigCameras = function () {
  22909. for (var i = 0; i < this._rigCameras.length; i++) {
  22910. this._rigCameras[i].minZ = this.minZ;
  22911. this._rigCameras[i].maxZ = this.maxZ;
  22912. this._rigCameras[i].fov = this.fov;
  22913. }
  22914. // only update viewport when ANAGLYPH
  22915. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22916. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22917. }
  22918. };
  22919. /** @hidden */
  22920. Camera.prototype._setupInputs = function () {
  22921. };
  22922. Camera.prototype.serialize = function () {
  22923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22924. // Type
  22925. serializationObject.type = this.getClassName();
  22926. // Parent
  22927. if (this.parent) {
  22928. serializationObject.parentId = this.parent.id;
  22929. }
  22930. if (this.inputs) {
  22931. this.inputs.serialize(serializationObject);
  22932. }
  22933. // Animations
  22934. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22935. serializationObject.ranges = this.serializeAnimationRanges();
  22936. return serializationObject;
  22937. };
  22938. Camera.prototype.clone = function (name) {
  22939. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22940. };
  22941. Camera.prototype.getDirection = function (localAxis) {
  22942. var result = BABYLON.Vector3.Zero();
  22943. this.getDirectionToRef(localAxis, result);
  22944. return result;
  22945. };
  22946. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22947. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22948. };
  22949. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22950. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22951. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22952. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22953. interaxial_distance: interaxial_distance,
  22954. isStereoscopicSideBySide: isStereoscopicSideBySide
  22955. });
  22956. if (constructorFunc) {
  22957. return constructorFunc;
  22958. }
  22959. // Default to universal camera
  22960. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22961. };
  22962. Camera.prototype.computeWorldMatrix = function () {
  22963. return this.getWorldMatrix();
  22964. };
  22965. Camera.Parse = function (parsedCamera, scene) {
  22966. var type = parsedCamera.type;
  22967. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22968. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22969. // Parent
  22970. if (parsedCamera.parentId) {
  22971. camera._waitingParentId = parsedCamera.parentId;
  22972. }
  22973. //If camera has an input manager, let it parse inputs settings
  22974. if (camera.inputs) {
  22975. camera.inputs.parse(parsedCamera);
  22976. camera._setupInputs();
  22977. }
  22978. if (camera.setPosition) { // need to force position
  22979. camera.position.copyFromFloats(0, 0, 0);
  22980. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22981. }
  22982. // Target
  22983. if (parsedCamera.target) {
  22984. if (camera.setTarget) {
  22985. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22986. }
  22987. }
  22988. // Apply 3d rig, when found
  22989. if (parsedCamera.cameraRigMode) {
  22990. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22991. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22992. }
  22993. // Animations
  22994. if (parsedCamera.animations) {
  22995. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22996. var parsedAnimation = parsedCamera.animations[animationIndex];
  22997. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22998. }
  22999. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23000. }
  23001. if (parsedCamera.autoAnimate) {
  23002. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23003. }
  23004. return camera;
  23005. };
  23006. // Statics
  23007. Camera._PERSPECTIVE_CAMERA = 0;
  23008. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23009. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23010. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23011. Camera._RIG_MODE_NONE = 0;
  23012. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23013. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23014. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23015. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23016. Camera._RIG_MODE_VR = 20;
  23017. Camera._RIG_MODE_WEBVR = 21;
  23018. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23019. Camera.UseAlternateWebVRRendering = false;
  23020. __decorate([
  23021. BABYLON.serializeAsVector3()
  23022. ], Camera.prototype, "position", void 0);
  23023. __decorate([
  23024. BABYLON.serializeAsVector3()
  23025. ], Camera.prototype, "upVector", void 0);
  23026. __decorate([
  23027. BABYLON.serialize()
  23028. ], Camera.prototype, "orthoLeft", void 0);
  23029. __decorate([
  23030. BABYLON.serialize()
  23031. ], Camera.prototype, "orthoRight", void 0);
  23032. __decorate([
  23033. BABYLON.serialize()
  23034. ], Camera.prototype, "orthoBottom", void 0);
  23035. __decorate([
  23036. BABYLON.serialize()
  23037. ], Camera.prototype, "orthoTop", void 0);
  23038. __decorate([
  23039. BABYLON.serialize()
  23040. ], Camera.prototype, "fov", void 0);
  23041. __decorate([
  23042. BABYLON.serialize()
  23043. ], Camera.prototype, "minZ", void 0);
  23044. __decorate([
  23045. BABYLON.serialize()
  23046. ], Camera.prototype, "maxZ", void 0);
  23047. __decorate([
  23048. BABYLON.serialize()
  23049. ], Camera.prototype, "inertia", void 0);
  23050. __decorate([
  23051. BABYLON.serialize()
  23052. ], Camera.prototype, "mode", void 0);
  23053. __decorate([
  23054. BABYLON.serialize()
  23055. ], Camera.prototype, "layerMask", void 0);
  23056. __decorate([
  23057. BABYLON.serialize()
  23058. ], Camera.prototype, "fovMode", void 0);
  23059. __decorate([
  23060. BABYLON.serialize()
  23061. ], Camera.prototype, "cameraRigMode", void 0);
  23062. __decorate([
  23063. BABYLON.serialize()
  23064. ], Camera.prototype, "interaxialDistance", void 0);
  23065. __decorate([
  23066. BABYLON.serialize()
  23067. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23068. return Camera;
  23069. }(BABYLON.Node));
  23070. BABYLON.Camera = Camera;
  23071. })(BABYLON || (BABYLON = {}));
  23072. //# sourceMappingURL=babylon.camera.js.map
  23073. var BABYLON;
  23074. (function (BABYLON) {
  23075. var RenderingManager = /** @class */ (function () {
  23076. function RenderingManager(scene) {
  23077. /**
  23078. * @hidden
  23079. */
  23080. this._useSceneAutoClearSetup = false;
  23081. this._renderingGroups = new Array();
  23082. this._autoClearDepthStencil = {};
  23083. this._customOpaqueSortCompareFn = {};
  23084. this._customAlphaTestSortCompareFn = {};
  23085. this._customTransparentSortCompareFn = {};
  23086. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23087. this._scene = scene;
  23088. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23089. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23090. }
  23091. }
  23092. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23093. if (depth === void 0) { depth = true; }
  23094. if (stencil === void 0) { stencil = true; }
  23095. if (this._depthStencilBufferAlreadyCleaned) {
  23096. return;
  23097. }
  23098. this._scene.getEngine().clear(null, false, depth, stencil);
  23099. this._depthStencilBufferAlreadyCleaned = true;
  23100. };
  23101. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23102. // Update the observable context (not null as it only goes away on dispose)
  23103. var info = this._renderingGroupInfo;
  23104. info.scene = this._scene;
  23105. info.camera = this._scene.activeCamera;
  23106. // Dispatch sprites
  23107. if (renderSprites) {
  23108. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23109. var manager = this._scene.spriteManagers[index];
  23110. this.dispatchSprites(manager);
  23111. }
  23112. }
  23113. // Render
  23114. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23115. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23116. var renderingGroup = this._renderingGroups[index];
  23117. if (!renderingGroup)
  23118. continue;
  23119. var renderingGroupMask = Math.pow(2, index);
  23120. info.renderingGroupId = index;
  23121. // Before Observable
  23122. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23123. // Clear depth/stencil if needed
  23124. if (RenderingManager.AUTOCLEAR) {
  23125. var autoClear = this._useSceneAutoClearSetup ?
  23126. this._scene.getAutoClearDepthStencilSetup(index) :
  23127. this._autoClearDepthStencil[index];
  23128. if (autoClear && autoClear.autoClear) {
  23129. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23130. }
  23131. }
  23132. // Render
  23133. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23134. var step = _a[_i];
  23135. step.action(index);
  23136. }
  23137. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23138. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23139. var step = _c[_b];
  23140. step.action(index);
  23141. }
  23142. // After Observable
  23143. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23144. }
  23145. };
  23146. RenderingManager.prototype.reset = function () {
  23147. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23148. var renderingGroup = this._renderingGroups[index];
  23149. if (renderingGroup) {
  23150. renderingGroup.prepare();
  23151. }
  23152. }
  23153. };
  23154. RenderingManager.prototype.dispose = function () {
  23155. this.freeRenderingGroups();
  23156. this._renderingGroups.length = 0;
  23157. this._renderingGroupInfo = null;
  23158. };
  23159. /**
  23160. * Clear the info related to rendering groups preventing retention points during dispose.
  23161. */
  23162. RenderingManager.prototype.freeRenderingGroups = function () {
  23163. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23164. var renderingGroup = this._renderingGroups[index];
  23165. if (renderingGroup) {
  23166. renderingGroup.dispose();
  23167. }
  23168. }
  23169. };
  23170. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23171. if (this._renderingGroups[renderingGroupId] === undefined) {
  23172. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23173. }
  23174. };
  23175. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23176. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23177. this._prepareRenderingGroup(renderingGroupId);
  23178. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23179. };
  23180. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23181. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23182. this._prepareRenderingGroup(renderingGroupId);
  23183. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23184. };
  23185. /**
  23186. * @param subMesh The submesh to dispatch
  23187. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23188. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23189. */
  23190. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23191. if (mesh === undefined) {
  23192. mesh = subMesh.getMesh();
  23193. }
  23194. var renderingGroupId = mesh.renderingGroupId || 0;
  23195. this._prepareRenderingGroup(renderingGroupId);
  23196. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23197. };
  23198. /**
  23199. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23200. * This allowed control for front to back rendering or reversly depending of the special needs.
  23201. *
  23202. * @param renderingGroupId The rendering group id corresponding to its index
  23203. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23204. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23205. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23206. */
  23207. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23208. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23209. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23210. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23211. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23212. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23213. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23214. if (this._renderingGroups[renderingGroupId]) {
  23215. var group = this._renderingGroups[renderingGroupId];
  23216. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23217. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23218. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23219. }
  23220. };
  23221. /**
  23222. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23223. *
  23224. * @param renderingGroupId The rendering group id corresponding to its index
  23225. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23226. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23227. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23228. */
  23229. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23230. if (depth === void 0) { depth = true; }
  23231. if (stencil === void 0) { stencil = true; }
  23232. this._autoClearDepthStencil[renderingGroupId] = {
  23233. autoClear: autoClearDepthStencil,
  23234. depth: depth,
  23235. stencil: stencil
  23236. };
  23237. };
  23238. /**
  23239. * Gets the current auto clear configuration for one rendering group of the rendering
  23240. * manager.
  23241. * @param index the rendering group index to get the information for
  23242. * @returns The auto clear setup for the requested rendering group
  23243. */
  23244. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23245. return this._autoClearDepthStencil[index];
  23246. };
  23247. /**
  23248. * The max id used for rendering groups (not included)
  23249. */
  23250. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23251. /**
  23252. * The min id used for rendering groups (included)
  23253. */
  23254. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23255. /**
  23256. * Used to globally prevent autoclearing scenes.
  23257. */
  23258. RenderingManager.AUTOCLEAR = true;
  23259. return RenderingManager;
  23260. }());
  23261. BABYLON.RenderingManager = RenderingManager;
  23262. })(BABYLON || (BABYLON = {}));
  23263. //# sourceMappingURL=babylon.renderingManager.js.map
  23264. var BABYLON;
  23265. (function (BABYLON) {
  23266. var RenderingGroup = /** @class */ (function () {
  23267. /**
  23268. * Creates a new rendering group.
  23269. * @param index The rendering group index
  23270. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23271. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23272. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23273. */
  23274. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23275. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23276. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23277. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23278. this.index = index;
  23279. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23280. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23281. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23282. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23283. this._particleSystems = new BABYLON.SmartArray(256);
  23284. this._spriteManagers = new BABYLON.SmartArray(256);
  23285. this._edgesRenderers = new BABYLON.SmartArray(16);
  23286. this._scene = scene;
  23287. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23288. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23289. this.transparentSortCompareFn = transparentSortCompareFn;
  23290. }
  23291. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23292. /**
  23293. * Set the opaque sort comparison function.
  23294. * If null the sub meshes will be render in the order they were created
  23295. */
  23296. set: function (value) {
  23297. this._opaqueSortCompareFn = value;
  23298. if (value) {
  23299. this._renderOpaque = this.renderOpaqueSorted;
  23300. }
  23301. else {
  23302. this._renderOpaque = RenderingGroup.renderUnsorted;
  23303. }
  23304. },
  23305. enumerable: true,
  23306. configurable: true
  23307. });
  23308. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23309. /**
  23310. * Set the alpha test sort comparison function.
  23311. * If null the sub meshes will be render in the order they were created
  23312. */
  23313. set: function (value) {
  23314. this._alphaTestSortCompareFn = value;
  23315. if (value) {
  23316. this._renderAlphaTest = this.renderAlphaTestSorted;
  23317. }
  23318. else {
  23319. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23320. }
  23321. },
  23322. enumerable: true,
  23323. configurable: true
  23324. });
  23325. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23326. /**
  23327. * Set the transparent sort comparison function.
  23328. * If null the sub meshes will be render in the order they were created
  23329. */
  23330. set: function (value) {
  23331. if (value) {
  23332. this._transparentSortCompareFn = value;
  23333. }
  23334. else {
  23335. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23336. }
  23337. this._renderTransparent = this.renderTransparentSorted;
  23338. },
  23339. enumerable: true,
  23340. configurable: true
  23341. });
  23342. /**
  23343. * Render all the sub meshes contained in the group.
  23344. * @param customRenderFunction Used to override the default render behaviour of the group.
  23345. * @returns true if rendered some submeshes.
  23346. */
  23347. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23348. if (customRenderFunction) {
  23349. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23350. return;
  23351. }
  23352. var engine = this._scene.getEngine();
  23353. // Depth only
  23354. if (this._depthOnlySubMeshes.length !== 0) {
  23355. engine.setColorWrite(false);
  23356. this._renderAlphaTest(this._depthOnlySubMeshes);
  23357. engine.setColorWrite(true);
  23358. }
  23359. // Opaque
  23360. if (this._opaqueSubMeshes.length !== 0) {
  23361. this._renderOpaque(this._opaqueSubMeshes);
  23362. }
  23363. // Alpha test
  23364. if (this._alphaTestSubMeshes.length !== 0) {
  23365. this._renderAlphaTest(this._alphaTestSubMeshes);
  23366. }
  23367. var stencilState = engine.getStencilBuffer();
  23368. engine.setStencilBuffer(false);
  23369. // Sprites
  23370. if (renderSprites) {
  23371. this._renderSprites();
  23372. }
  23373. // Particles
  23374. if (renderParticles) {
  23375. this._renderParticles(activeMeshes);
  23376. }
  23377. if (this.onBeforeTransparentRendering) {
  23378. this.onBeforeTransparentRendering();
  23379. }
  23380. // Transparent
  23381. if (this._transparentSubMeshes.length !== 0) {
  23382. this._renderTransparent(this._transparentSubMeshes);
  23383. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23384. }
  23385. // Set back stencil to false in case it changes before the edge renderer.
  23386. engine.setStencilBuffer(false);
  23387. // Edges
  23388. if (this._edgesRenderers.length) {
  23389. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23390. this._edgesRenderers.data[edgesRendererIndex].render();
  23391. }
  23392. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23393. }
  23394. // Restore Stencil state.
  23395. engine.setStencilBuffer(stencilState);
  23396. };
  23397. /**
  23398. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23399. * @param subMeshes The submeshes to render
  23400. */
  23401. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23402. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23403. };
  23404. /**
  23405. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23406. * @param subMeshes The submeshes to render
  23407. */
  23408. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23409. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23410. };
  23411. /**
  23412. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23413. * @param subMeshes The submeshes to render
  23414. */
  23415. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23416. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23417. };
  23418. /**
  23419. * Renders the submeshes in a specified order.
  23420. * @param subMeshes The submeshes to sort before render
  23421. * @param sortCompareFn The comparison function use to sort
  23422. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23423. * @param transparent Specifies to activate blending if true
  23424. */
  23425. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23426. var subIndex = 0;
  23427. var subMesh;
  23428. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23429. for (; subIndex < subMeshes.length; subIndex++) {
  23430. subMesh = subMeshes.data[subIndex];
  23431. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23432. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23433. }
  23434. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23435. if (sortCompareFn) {
  23436. sortedArray.sort(sortCompareFn);
  23437. }
  23438. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23439. subMesh = sortedArray[subIndex];
  23440. if (transparent) {
  23441. var material = subMesh.getMaterial();
  23442. if (material && material.needDepthPrePass) {
  23443. var engine = material.getScene().getEngine();
  23444. engine.setColorWrite(false);
  23445. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23446. subMesh.render(false);
  23447. engine.setColorWrite(true);
  23448. }
  23449. }
  23450. subMesh.render(transparent);
  23451. }
  23452. };
  23453. /**
  23454. * Renders the submeshes in the order they were dispatched (no sort applied).
  23455. * @param subMeshes The submeshes to render
  23456. */
  23457. RenderingGroup.renderUnsorted = function (subMeshes) {
  23458. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23459. var submesh = subMeshes.data[subIndex];
  23460. submesh.render(false);
  23461. }
  23462. };
  23463. /**
  23464. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23465. * are rendered back to front if in the same alpha index.
  23466. *
  23467. * @param a The first submesh
  23468. * @param b The second submesh
  23469. * @returns The result of the comparison
  23470. */
  23471. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23472. // Alpha index first
  23473. if (a._alphaIndex > b._alphaIndex) {
  23474. return 1;
  23475. }
  23476. if (a._alphaIndex < b._alphaIndex) {
  23477. return -1;
  23478. }
  23479. // Then distance to camera
  23480. return RenderingGroup.backToFrontSortCompare(a, b);
  23481. };
  23482. /**
  23483. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23484. * are rendered back to front.
  23485. *
  23486. * @param a The first submesh
  23487. * @param b The second submesh
  23488. * @returns The result of the comparison
  23489. */
  23490. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23491. // Then distance to camera
  23492. if (a._distanceToCamera < b._distanceToCamera) {
  23493. return 1;
  23494. }
  23495. if (a._distanceToCamera > b._distanceToCamera) {
  23496. return -1;
  23497. }
  23498. return 0;
  23499. };
  23500. /**
  23501. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23502. * are rendered front to back (prevent overdraw).
  23503. *
  23504. * @param a The first submesh
  23505. * @param b The second submesh
  23506. * @returns The result of the comparison
  23507. */
  23508. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23509. // Then distance to camera
  23510. if (a._distanceToCamera < b._distanceToCamera) {
  23511. return -1;
  23512. }
  23513. if (a._distanceToCamera > b._distanceToCamera) {
  23514. return 1;
  23515. }
  23516. return 0;
  23517. };
  23518. /**
  23519. * Resets the different lists of submeshes to prepare a new frame.
  23520. */
  23521. RenderingGroup.prototype.prepare = function () {
  23522. this._opaqueSubMeshes.reset();
  23523. this._transparentSubMeshes.reset();
  23524. this._alphaTestSubMeshes.reset();
  23525. this._depthOnlySubMeshes.reset();
  23526. this._particleSystems.reset();
  23527. this._spriteManagers.reset();
  23528. this._edgesRenderers.reset();
  23529. };
  23530. RenderingGroup.prototype.dispose = function () {
  23531. this._opaqueSubMeshes.dispose();
  23532. this._transparentSubMeshes.dispose();
  23533. this._alphaTestSubMeshes.dispose();
  23534. this._depthOnlySubMeshes.dispose();
  23535. this._particleSystems.dispose();
  23536. this._spriteManagers.dispose();
  23537. this._edgesRenderers.dispose();
  23538. };
  23539. /**
  23540. * Inserts the submesh in its correct queue depending on its material.
  23541. * @param subMesh The submesh to dispatch
  23542. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23543. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23544. */
  23545. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23546. // Get mesh and materials if not provided
  23547. if (mesh === undefined) {
  23548. mesh = subMesh.getMesh();
  23549. }
  23550. if (material === undefined) {
  23551. material = subMesh.getMaterial();
  23552. }
  23553. if (material === null || material === undefined) {
  23554. return;
  23555. }
  23556. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23557. this._transparentSubMeshes.push(subMesh);
  23558. }
  23559. else if (material.needAlphaTesting()) { // Alpha test
  23560. if (material.needDepthPrePass) {
  23561. this._depthOnlySubMeshes.push(subMesh);
  23562. }
  23563. this._alphaTestSubMeshes.push(subMesh);
  23564. }
  23565. else {
  23566. if (material.needDepthPrePass) {
  23567. this._depthOnlySubMeshes.push(subMesh);
  23568. }
  23569. this._opaqueSubMeshes.push(subMesh); // Opaque
  23570. }
  23571. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23572. this._edgesRenderers.push(mesh._edgesRenderer);
  23573. }
  23574. };
  23575. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23576. this._spriteManagers.push(spriteManager);
  23577. };
  23578. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23579. this._particleSystems.push(particleSystem);
  23580. };
  23581. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23582. if (this._particleSystems.length === 0) {
  23583. return;
  23584. }
  23585. // Particles
  23586. var activeCamera = this._scene.activeCamera;
  23587. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23588. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23589. var particleSystem = this._particleSystems.data[particleIndex];
  23590. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23591. continue;
  23592. }
  23593. var emitter = particleSystem.emitter;
  23594. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23595. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23596. }
  23597. }
  23598. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23599. };
  23600. RenderingGroup.prototype._renderSprites = function () {
  23601. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23602. return;
  23603. }
  23604. // Sprites
  23605. var activeCamera = this._scene.activeCamera;
  23606. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23607. for (var id = 0; id < this._spriteManagers.length; id++) {
  23608. var spriteManager = this._spriteManagers.data[id];
  23609. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23610. spriteManager.render();
  23611. }
  23612. }
  23613. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23614. };
  23615. return RenderingGroup;
  23616. }());
  23617. BABYLON.RenderingGroup = RenderingGroup;
  23618. })(BABYLON || (BABYLON = {}));
  23619. //# sourceMappingURL=babylon.renderingGroup.js.map
  23620. var BABYLON;
  23621. (function (BABYLON) {
  23622. /**
  23623. * Groups all the scene component constants in one place to ease maintenance.
  23624. * @hidden
  23625. */
  23626. var SceneComponentConstants = /** @class */ (function () {
  23627. function SceneComponentConstants() {
  23628. }
  23629. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23630. SceneComponentConstants.NAME_LAYER = "Layer";
  23631. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23632. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23633. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23634. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23635. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23636. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23637. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23638. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23639. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23640. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23641. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23642. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23643. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23644. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23645. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23646. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23647. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23648. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23649. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23650. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23651. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23652. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23653. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23654. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 0;
  23655. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 1;
  23656. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 2;
  23657. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23658. return SceneComponentConstants;
  23659. }());
  23660. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23661. /**
  23662. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23663. * @hidden
  23664. */
  23665. var Stage = /** @class */ (function (_super) {
  23666. __extends(Stage, _super);
  23667. /**
  23668. * Hide ctor from the rest of the world.
  23669. * @param items The items to add.
  23670. */
  23671. function Stage(items) {
  23672. return _super.apply(this, items) || this;
  23673. }
  23674. /**
  23675. * Creates a new Stage.
  23676. * @returns A new instance of a Stage
  23677. */
  23678. Stage.Create = function () {
  23679. return Object.create(Stage.prototype);
  23680. };
  23681. /**
  23682. * Registers a step in an ordered way in the targeted stage.
  23683. * @param index Defines the position to register the step in
  23684. * @param component Defines the component attached to the step
  23685. * @param action Defines the action to launch during the step
  23686. */
  23687. Stage.prototype.registerStep = function (index, component, action) {
  23688. var i = 0;
  23689. var maxIndex = Number.MAX_VALUE;
  23690. for (; i < this.length && i < maxIndex; i++) {
  23691. var step = this[i];
  23692. maxIndex = step.index;
  23693. }
  23694. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23695. };
  23696. /**
  23697. * Clears all the steps from the stage.
  23698. */
  23699. Stage.prototype.clear = function () {
  23700. this.length = 0;
  23701. };
  23702. return Stage;
  23703. }(Array));
  23704. BABYLON.Stage = Stage;
  23705. })(BABYLON || (BABYLON = {}));
  23706. //# sourceMappingURL=babylon.sceneComponent.js.map
  23707. var BABYLON;
  23708. (function (BABYLON) {
  23709. /**
  23710. * Base class of the scene acting as a container for the different elements composing a scene.
  23711. * This class is dynamically extended by the different components of the scene increasing
  23712. * flexibility and reducing coupling
  23713. */
  23714. var AbstractScene = /** @class */ (function () {
  23715. function AbstractScene() {
  23716. /** All of the cameras added to this scene
  23717. * @see http://doc.babylonjs.com/babylon101/cameras
  23718. */
  23719. this.cameras = new Array();
  23720. /**
  23721. * All of the lights added to this scene
  23722. * @see http://doc.babylonjs.com/babylon101/lights
  23723. */
  23724. this.lights = new Array();
  23725. /**
  23726. * All of the (abstract) meshes added to this scene
  23727. */
  23728. this.meshes = new Array();
  23729. /**
  23730. * The list of skeletons added to the scene
  23731. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23732. */
  23733. this.skeletons = new Array();
  23734. /**
  23735. * All of the particle systems added to this scene
  23736. * @see http://doc.babylonjs.com/babylon101/particles
  23737. */
  23738. this.particleSystems = new Array();
  23739. /**
  23740. * Gets a list of Animations associated with the scene
  23741. */
  23742. this.animations = [];
  23743. /**
  23744. * All of the animation groups added to this scene
  23745. * @see http://doc.babylonjs.com/how_to/group
  23746. */
  23747. this.animationGroups = new Array();
  23748. /**
  23749. * All of the multi-materials added to this scene
  23750. * @see http://doc.babylonjs.com/how_to/multi_materials
  23751. */
  23752. this.multiMaterials = new Array();
  23753. /**
  23754. * All of the materials added to this scene
  23755. * @see http://doc.babylonjs.com/babylon101/materials
  23756. */
  23757. this.materials = new Array();
  23758. /**
  23759. * The list of morph target managers added to the scene
  23760. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23761. */
  23762. this.morphTargetManagers = new Array();
  23763. /**
  23764. * The list of geometries used in the scene.
  23765. */
  23766. this.geometries = new Array();
  23767. /**
  23768. * All of the tranform nodes added to this scene
  23769. * @see http://doc.babylonjs.com/how_to/transformnode
  23770. */
  23771. this.transformNodes = new Array();
  23772. /**
  23773. * ActionManagers available on the scene.
  23774. */
  23775. this.actionManagers = new Array();
  23776. /**
  23777. * Sounds to keep.
  23778. */
  23779. this.sounds = new Array();
  23780. /**
  23781. * Textures to keep.
  23782. */
  23783. this.textures = new Array();
  23784. }
  23785. /**
  23786. * Adds a parser in the list of available ones
  23787. * @param name Defines the name of the parser
  23788. * @param parser Defines the parser to add
  23789. */
  23790. AbstractScene.AddParser = function (name, parser) {
  23791. this._BabylonFileParsers[name] = parser;
  23792. };
  23793. /**
  23794. * Gets a general parser from the list of avaialble ones
  23795. * @param name Defines the name of the parser
  23796. * @returns the requested parser or null
  23797. */
  23798. AbstractScene.GetParser = function (name) {
  23799. if (this._BabylonFileParsers[name]) {
  23800. return this._BabylonFileParsers[name];
  23801. }
  23802. return null;
  23803. };
  23804. /**
  23805. * Adds n individual parser in the list of available ones
  23806. * @param name Defines the name of the parser
  23807. * @param parser Defines the parser to add
  23808. */
  23809. AbstractScene.AddIndividualParser = function (name, parser) {
  23810. this._IndividualBabylonFileParsers[name] = parser;
  23811. };
  23812. /**
  23813. * Gets an individual parser from the list of avaialble ones
  23814. * @param name Defines the name of the parser
  23815. * @returns the requested parser or null
  23816. */
  23817. AbstractScene.GetIndividualParser = function (name) {
  23818. if (this._IndividualBabylonFileParsers[name]) {
  23819. return this._IndividualBabylonFileParsers[name];
  23820. }
  23821. return null;
  23822. };
  23823. /**
  23824. * Parser json data and populate both a scene and its associated container object
  23825. * @param jsonData Defines the data to parse
  23826. * @param scene Defines the scene to parse the data for
  23827. * @param container Defines the container attached to the parsing sequence
  23828. * @param rootUrl Defines the root url of the data
  23829. */
  23830. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23831. for (var parserName in this._BabylonFileParsers) {
  23832. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23833. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23834. }
  23835. }
  23836. };
  23837. /**
  23838. * Stores the list of available parsers in the application.
  23839. */
  23840. AbstractScene._BabylonFileParsers = {};
  23841. /**
  23842. * Stores the list of available individual parsers in the application.
  23843. */
  23844. AbstractScene._IndividualBabylonFileParsers = {};
  23845. return AbstractScene;
  23846. }());
  23847. BABYLON.AbstractScene = AbstractScene;
  23848. })(BABYLON || (BABYLON = {}));
  23849. //# sourceMappingURL=babylon.abstractScene.js.map
  23850. var BABYLON;
  23851. (function (BABYLON) {
  23852. /** @hidden */
  23853. var ClickInfo = /** @class */ (function () {
  23854. function ClickInfo() {
  23855. this._singleClick = false;
  23856. this._doubleClick = false;
  23857. this._hasSwiped = false;
  23858. this._ignore = false;
  23859. }
  23860. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23861. get: function () {
  23862. return this._singleClick;
  23863. },
  23864. set: function (b) {
  23865. this._singleClick = b;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23871. get: function () {
  23872. return this._doubleClick;
  23873. },
  23874. set: function (b) {
  23875. this._doubleClick = b;
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23881. get: function () {
  23882. return this._hasSwiped;
  23883. },
  23884. set: function (b) {
  23885. this._hasSwiped = b;
  23886. },
  23887. enumerable: true,
  23888. configurable: true
  23889. });
  23890. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23891. get: function () {
  23892. return this._ignore;
  23893. },
  23894. set: function (b) {
  23895. this._ignore = b;
  23896. },
  23897. enumerable: true,
  23898. configurable: true
  23899. });
  23900. return ClickInfo;
  23901. }());
  23902. /**
  23903. * This class is used by the onRenderingGroupObservable
  23904. */
  23905. var RenderingGroupInfo = /** @class */ (function () {
  23906. function RenderingGroupInfo() {
  23907. }
  23908. return RenderingGroupInfo;
  23909. }());
  23910. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23911. /**
  23912. * Represents a scene to be rendered by the engine.
  23913. * @see http://doc.babylonjs.com/features/scene
  23914. */
  23915. var Scene = /** @class */ (function (_super) {
  23916. __extends(Scene, _super);
  23917. /**
  23918. * Creates a new Scene
  23919. * @param engine defines the engine to use to render this scene
  23920. */
  23921. function Scene(engine) {
  23922. var _this = _super.call(this) || this;
  23923. // Members
  23924. /**
  23925. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23926. */
  23927. _this.autoClear = true;
  23928. /**
  23929. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23930. */
  23931. _this.autoClearDepthAndStencil = true;
  23932. /**
  23933. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23934. */
  23935. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23936. /**
  23937. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23938. */
  23939. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23940. _this._forceWireframe = false;
  23941. _this._forcePointsCloud = false;
  23942. /**
  23943. * Gets or sets a boolean indicating if animations are enabled
  23944. */
  23945. _this.animationsEnabled = true;
  23946. _this._animationPropertiesOverride = null;
  23947. /**
  23948. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23949. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23950. */
  23951. _this.useConstantAnimationDeltaTime = false;
  23952. /**
  23953. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23954. * Please note that it requires to run a ray cast through the scene on every frame
  23955. */
  23956. _this.constantlyUpdateMeshUnderPointer = false;
  23957. /**
  23958. * Defines the HTML cursor to use when hovering over interactive elements
  23959. */
  23960. _this.hoverCursor = "pointer";
  23961. /**
  23962. * Defines the HTML default cursor to use (empty by default)
  23963. */
  23964. _this.defaultCursor = "";
  23965. /**
  23966. * This is used to call preventDefault() on pointer down
  23967. * in order to block unwanted artifacts like system double clicks
  23968. */
  23969. _this.preventDefaultOnPointerDown = true;
  23970. // Metadata
  23971. /**
  23972. * Gets or sets user defined metadata
  23973. */
  23974. _this.metadata = null;
  23975. /**
  23976. * Use this array to add regular expressions used to disable offline support for specific urls
  23977. */
  23978. _this.disableOfflineSupportExceptionRules = new Array();
  23979. /**
  23980. * An event triggered when the scene is disposed.
  23981. */
  23982. _this.onDisposeObservable = new BABYLON.Observable();
  23983. _this._onDisposeObserver = null;
  23984. /**
  23985. * An event triggered before rendering the scene (right after animations and physics)
  23986. */
  23987. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23988. _this._onBeforeRenderObserver = null;
  23989. /**
  23990. * An event triggered after rendering the scene
  23991. */
  23992. _this.onAfterRenderObservable = new BABYLON.Observable();
  23993. _this._onAfterRenderObserver = null;
  23994. /**
  23995. * An event triggered before animating the scene
  23996. */
  23997. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23998. /**
  23999. * An event triggered after animations processing
  24000. */
  24001. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24002. /**
  24003. * An event triggered before draw calls are ready to be sent
  24004. */
  24005. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24006. /**
  24007. * An event triggered after draw calls have been sent
  24008. */
  24009. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered when physic simulation is about to be run
  24012. */
  24013. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when physic simulation has been done
  24016. */
  24017. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when the scene is ready
  24020. */
  24021. _this.onReadyObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered before rendering a camera
  24024. */
  24025. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24026. _this._onBeforeCameraRenderObserver = null;
  24027. /**
  24028. * An event triggered after rendering a camera
  24029. */
  24030. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24031. _this._onAfterCameraRenderObserver = null;
  24032. /**
  24033. * An event triggered when active meshes evaluation is about to start
  24034. */
  24035. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when active meshes evaluation is done
  24038. */
  24039. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24040. /**
  24041. * An event triggered when particles rendering is about to start
  24042. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24043. */
  24044. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when particles rendering is done
  24047. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24048. */
  24049. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when sprites rendering is about to start
  24052. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24053. */
  24054. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24055. /**
  24056. * An event triggered when sprites rendering is done
  24057. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24058. */
  24059. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24060. /**
  24061. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24062. */
  24063. _this.onDataLoadedObservable = new BABYLON.Observable();
  24064. /**
  24065. * An event triggered when a camera is created
  24066. */
  24067. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24068. /**
  24069. * An event triggered when a camera is removed
  24070. */
  24071. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24072. /**
  24073. * An event triggered when a light is created
  24074. */
  24075. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24076. /**
  24077. * An event triggered when a light is removed
  24078. */
  24079. _this.onLightRemovedObservable = new BABYLON.Observable();
  24080. /**
  24081. * An event triggered when a geometry is created
  24082. */
  24083. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24084. /**
  24085. * An event triggered when a geometry is removed
  24086. */
  24087. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24088. /**
  24089. * An event triggered when a transform node is created
  24090. */
  24091. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered when a transform node is removed
  24094. */
  24095. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24096. /**
  24097. * An event triggered when a mesh is created
  24098. */
  24099. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24100. /**
  24101. * An event triggered when a mesh is removed
  24102. */
  24103. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24104. /**
  24105. * An event triggered when render targets are about to be rendered
  24106. * Can happen multiple times per frame.
  24107. */
  24108. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24109. /**
  24110. * An event triggered when render targets were rendered.
  24111. * Can happen multiple times per frame.
  24112. */
  24113. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24114. /**
  24115. * An event triggered before calculating deterministic simulation step
  24116. */
  24117. _this.onBeforeStepObservable = new BABYLON.Observable();
  24118. /**
  24119. * An event triggered after calculating deterministic simulation step
  24120. */
  24121. _this.onAfterStepObservable = new BABYLON.Observable();
  24122. /**
  24123. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24124. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24125. * 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)
  24126. */
  24127. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24128. /**
  24129. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24130. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24131. * 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)
  24132. */
  24133. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24134. // Animations
  24135. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24136. /**
  24137. * 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).
  24138. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24139. */
  24140. _this.onPrePointerObservable = new BABYLON.Observable();
  24141. /**
  24142. * Observable event triggered each time an input event is received from the rendering canvas
  24143. */
  24144. _this.onPointerObservable = new BABYLON.Observable();
  24145. _this._meshPickProceed = false;
  24146. _this._currentPickResult = null;
  24147. _this._previousPickResult = null;
  24148. _this._totalPointersPressed = 0;
  24149. _this._doubleClickOccured = false;
  24150. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24151. _this.cameraToUseForPointers = null;
  24152. _this._pointerX = 0;
  24153. _this._pointerY = 0;
  24154. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24155. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24156. _this._startingPointerTime = 0;
  24157. _this._previousStartingPointerTime = 0;
  24158. _this._pointerCaptures = {};
  24159. // Deterministic lockstep
  24160. _this._timeAccumulator = 0;
  24161. _this._currentStepId = 0;
  24162. _this._currentInternalStep = 0;
  24163. // Keyboard
  24164. /**
  24165. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24166. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24167. */
  24168. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24169. /**
  24170. * Observable event triggered each time an keyboard event is received from the hosting window
  24171. */
  24172. _this.onKeyboardObservable = new BABYLON.Observable();
  24173. // Coordinates system
  24174. _this._useRightHandedSystem = false;
  24175. // Fog
  24176. _this._fogEnabled = true;
  24177. _this._fogMode = Scene.FOGMODE_NONE;
  24178. /**
  24179. * Gets or sets the fog color to use
  24180. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24181. */
  24182. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24183. /**
  24184. * Gets or sets the fog density to use
  24185. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24186. */
  24187. _this.fogDensity = 0.1;
  24188. /**
  24189. * Gets or sets the fog start distance to use
  24190. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24191. */
  24192. _this.fogStart = 0;
  24193. /**
  24194. * Gets or sets the fog end distance to use
  24195. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24196. */
  24197. _this.fogEnd = 1000.0;
  24198. // Lights
  24199. _this._shadowsEnabled = true;
  24200. _this._lightsEnabled = true;
  24201. /** All of the active cameras added to this scene. */
  24202. _this.activeCameras = new Array();
  24203. // Textures
  24204. _this._texturesEnabled = true;
  24205. // Particles
  24206. /**
  24207. * Gets or sets a boolean indicating if particles are enabled on this scene
  24208. */
  24209. _this.particlesEnabled = true;
  24210. // Sprites
  24211. /**
  24212. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24213. */
  24214. _this.spritesEnabled = true;
  24215. /**
  24216. * All of the sprite managers added to this scene
  24217. * @see http://doc.babylonjs.com/babylon101/sprites
  24218. */
  24219. _this.spriteManagers = new Array();
  24220. // Skeletons
  24221. _this._skeletonsEnabled = true;
  24222. // Lens flares
  24223. /**
  24224. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24225. */
  24226. _this.lensFlaresEnabled = true;
  24227. // Collisions
  24228. /**
  24229. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24230. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24231. */
  24232. _this.collisionsEnabled = true;
  24233. /**
  24234. * Defines the gravity applied to this scene (used only for collisions)
  24235. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24236. */
  24237. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24238. // Postprocesses
  24239. /**
  24240. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24241. */
  24242. _this.postProcessesEnabled = true;
  24243. /**
  24244. * The list of postprocesses added to the scene
  24245. */
  24246. _this.postProcesses = new Array();
  24247. // Customs render targets
  24248. /**
  24249. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24250. */
  24251. _this.renderTargetsEnabled = true;
  24252. /**
  24253. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24254. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24255. */
  24256. _this.dumpNextRenderTargets = false;
  24257. /**
  24258. * The list of user defined render targets added to the scene
  24259. */
  24260. _this.customRenderTargets = new Array();
  24261. /**
  24262. * Gets the list of meshes imported to the scene through SceneLoader
  24263. */
  24264. _this.importedMeshesFiles = new Array();
  24265. // Probes
  24266. /**
  24267. * Gets or sets a boolean indicating if probes are enabled on this scene
  24268. */
  24269. _this.probesEnabled = true;
  24270. /**
  24271. * The list of reflection probes added to the scene
  24272. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24273. */
  24274. _this.reflectionProbes = new Array();
  24275. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24276. // Procedural textures
  24277. /**
  24278. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24279. */
  24280. _this.proceduralTexturesEnabled = true;
  24281. /**
  24282. * The list of procedural textures added to the scene
  24283. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24284. */
  24285. _this.proceduralTextures = new Array();
  24286. /**
  24287. * The list of sound tracks added to the scene
  24288. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24289. */
  24290. _this.soundTracks = new Array();
  24291. _this._audioEnabled = true;
  24292. _this._headphone = false;
  24293. // Performance counters
  24294. _this._totalVertices = new BABYLON.PerfCounter();
  24295. /** @hidden */
  24296. _this._activeIndices = new BABYLON.PerfCounter();
  24297. /** @hidden */
  24298. _this._activeParticles = new BABYLON.PerfCounter();
  24299. /** @hidden */
  24300. _this._activeBones = new BABYLON.PerfCounter();
  24301. _this._animationTime = 0;
  24302. /**
  24303. * Gets or sets a general scale for animation speed
  24304. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24305. */
  24306. _this.animationTimeScale = 1;
  24307. _this._renderId = 0;
  24308. _this._executeWhenReadyTimeoutId = -1;
  24309. _this._intermediateRendering = false;
  24310. _this._viewUpdateFlag = -1;
  24311. _this._projectionUpdateFlag = -1;
  24312. _this._alternateViewUpdateFlag = -1;
  24313. _this._alternateProjectionUpdateFlag = -1;
  24314. /** @hidden */
  24315. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24316. _this._activeRequests = new Array();
  24317. _this._pendingData = new Array();
  24318. _this._isDisposed = false;
  24319. /**
  24320. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24321. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24322. */
  24323. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24324. _this._activeMeshes = new BABYLON.SmartArray(256);
  24325. _this._processedMaterials = new BABYLON.SmartArray(256);
  24326. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24327. /** @hidden */
  24328. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24329. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24330. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24331. /** @hidden */
  24332. _this._activeAnimatables = new Array();
  24333. _this._transformMatrix = BABYLON.Matrix.Zero();
  24334. _this._useAlternateCameraConfiguration = false;
  24335. _this._alternateRendering = false;
  24336. /**
  24337. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24338. * This is useful if there are more lights that the maximum simulteanous authorized
  24339. */
  24340. _this.requireLightSorting = false;
  24341. /**
  24342. * @hidden
  24343. * Backing store of defined scene components.
  24344. */
  24345. _this._components = [];
  24346. /**
  24347. * @hidden
  24348. * Backing store of defined scene components.
  24349. */
  24350. _this._serializableComponents = [];
  24351. /**
  24352. * List of components to register on the next registration step.
  24353. */
  24354. _this._transientComponents = [];
  24355. /**
  24356. * @hidden
  24357. * Defines the actions happening before camera updates.
  24358. */
  24359. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24360. /**
  24361. * @hidden
  24362. * Defines the actions happening before camera updates.
  24363. */
  24364. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24365. /**
  24366. * @hidden
  24367. * Defines the actions happening during the per mesh ready checks.
  24368. */
  24369. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24370. /**
  24371. * @hidden
  24372. * Defines the actions happening before evaluate active mesh checks.
  24373. */
  24374. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24375. /**
  24376. * @hidden
  24377. * Defines the actions happening during the evaluate sub mesh checks.
  24378. */
  24379. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24380. /**
  24381. * @hidden
  24382. * Defines the actions happening during the active mesh stage.
  24383. */
  24384. _this._activeMeshStage = BABYLON.Stage.Create();
  24385. /**
  24386. * @hidden
  24387. * Defines the actions happening during the per camera render target step.
  24388. */
  24389. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24390. /**
  24391. * @hidden
  24392. * Defines the actions happening just before the active camera is drawing.
  24393. */
  24394. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24395. /**
  24396. * Defines the actions happening just before a rendering group is drawing.
  24397. */
  24398. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24399. /**
  24400. * @hidden
  24401. * Defines the actions happening just after a rendering group has been drawn.
  24402. */
  24403. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24404. /**
  24405. * @hidden
  24406. * Defines the actions happening just after the active camera has been drawn.
  24407. */
  24408. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24409. /**
  24410. * @hidden
  24411. * Defines the actions happening when Geometries are rebuilding.
  24412. */
  24413. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24414. _this._activeMeshesFrozen = false;
  24415. /** @hidden */
  24416. _this._allowPostProcessClear = true;
  24417. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24418. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24419. _this.blockMaterialDirtyMechanism = false;
  24420. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24421. _this._engine.scenes.push(_this);
  24422. _this._uid = null;
  24423. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24424. if (BABYLON.PostProcessManager) {
  24425. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24426. }
  24427. if (BABYLON.OutlineRenderer) {
  24428. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24429. }
  24430. if (BABYLON.Tools.IsWindowObjectExist()) {
  24431. _this.attachControl();
  24432. }
  24433. //collision coordinator initialization. For now legacy per default.
  24434. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24435. // Uniform Buffer
  24436. _this._createUbo();
  24437. // Default Image processing definition
  24438. if (BABYLON.ImageProcessingConfiguration) {
  24439. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24440. }
  24441. return _this;
  24442. }
  24443. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24444. /**
  24445. * Texture used in all pbr material as the reflection texture.
  24446. * As in the majority of the scene they are the same (exception for multi room and so on),
  24447. * this is easier to reference from here than from all the materials.
  24448. */
  24449. get: function () {
  24450. return this._environmentTexture;
  24451. },
  24452. /**
  24453. * Texture used in all pbr material as the reflection texture.
  24454. * As in the majority of the scene they are the same (exception for multi room and so on),
  24455. * this is easier to set here than in all the materials.
  24456. */
  24457. set: function (value) {
  24458. if (this._environmentTexture === value) {
  24459. return;
  24460. }
  24461. this._environmentTexture = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24468. /**
  24469. * Default image processing configuration used either in the rendering
  24470. * Forward main pass or through the imageProcessingPostProcess if present.
  24471. * As in the majority of the scene they are the same (exception for multi camera),
  24472. * this is easier to reference from here than from all the materials and post process.
  24473. *
  24474. * No setter as we it is a shared configuration, you can set the values instead.
  24475. */
  24476. get: function () {
  24477. return this._imageProcessingConfiguration;
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24483. get: function () {
  24484. return this._forceWireframe;
  24485. },
  24486. /**
  24487. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24488. */
  24489. set: function (value) {
  24490. if (this._forceWireframe === value) {
  24491. return;
  24492. }
  24493. this._forceWireframe = value;
  24494. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24500. get: function () {
  24501. return this._forcePointsCloud;
  24502. },
  24503. /**
  24504. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24505. */
  24506. set: function (value) {
  24507. if (this._forcePointsCloud === value) {
  24508. return;
  24509. }
  24510. this._forcePointsCloud = value;
  24511. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24517. /**
  24518. * Gets or sets the animation properties override
  24519. */
  24520. get: function () {
  24521. return this._animationPropertiesOverride;
  24522. },
  24523. set: function (value) {
  24524. this._animationPropertiesOverride = value;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "onDispose", {
  24530. /** Sets a function to be executed when this scene is disposed. */
  24531. set: function (callback) {
  24532. if (this._onDisposeObserver) {
  24533. this.onDisposeObservable.remove(this._onDisposeObserver);
  24534. }
  24535. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Scene.prototype, "beforeRender", {
  24541. /** Sets a function to be executed before rendering this scene */
  24542. set: function (callback) {
  24543. if (this._onBeforeRenderObserver) {
  24544. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24545. }
  24546. if (callback) {
  24547. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24548. }
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "afterRender", {
  24554. /** Sets a function to be executed after rendering this scene */
  24555. set: function (callback) {
  24556. if (this._onAfterRenderObserver) {
  24557. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24558. }
  24559. if (callback) {
  24560. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24561. }
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24567. /** Sets a function to be executed before rendering a camera*/
  24568. set: function (callback) {
  24569. if (this._onBeforeCameraRenderObserver) {
  24570. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24571. }
  24572. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24578. /** Sets a function to be executed after rendering a camera*/
  24579. set: function (callback) {
  24580. if (this._onAfterCameraRenderObserver) {
  24581. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24582. }
  24583. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24589. /**
  24590. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24591. */
  24592. get: function () {
  24593. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24594. },
  24595. enumerable: true,
  24596. configurable: true
  24597. });
  24598. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24599. get: function () {
  24600. return this._useRightHandedSystem;
  24601. },
  24602. /**
  24603. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24604. */
  24605. set: function (value) {
  24606. if (this._useRightHandedSystem === value) {
  24607. return;
  24608. }
  24609. this._useRightHandedSystem = value;
  24610. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. /**
  24616. * Sets the step Id used by deterministic lock step
  24617. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24618. * @param newStepId defines the step Id
  24619. */
  24620. Scene.prototype.setStepId = function (newStepId) {
  24621. this._currentStepId = newStepId;
  24622. };
  24623. ;
  24624. /**
  24625. * Gets the step Id used by deterministic lock step
  24626. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24627. * @returns the step Id
  24628. */
  24629. Scene.prototype.getStepId = function () {
  24630. return this._currentStepId;
  24631. };
  24632. ;
  24633. /**
  24634. * Gets the internal step used by deterministic lock step
  24635. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24636. * @returns the internal step
  24637. */
  24638. Scene.prototype.getInternalStep = function () {
  24639. return this._currentInternalStep;
  24640. };
  24641. ;
  24642. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24643. get: function () {
  24644. return this._fogEnabled;
  24645. },
  24646. /**
  24647. * Gets or sets a boolean indicating if fog is enabled on this scene
  24648. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24649. */
  24650. set: function (value) {
  24651. if (this._fogEnabled === value) {
  24652. return;
  24653. }
  24654. this._fogEnabled = value;
  24655. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Object.defineProperty(Scene.prototype, "fogMode", {
  24661. get: function () {
  24662. return this._fogMode;
  24663. },
  24664. /**
  24665. * Gets or sets the fog mode to use
  24666. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24667. */
  24668. set: function (value) {
  24669. if (this._fogMode === value) {
  24670. return;
  24671. }
  24672. this._fogMode = value;
  24673. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24679. get: function () {
  24680. return this._shadowsEnabled;
  24681. },
  24682. /**
  24683. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24684. */
  24685. set: function (value) {
  24686. if (this._shadowsEnabled === value) {
  24687. return;
  24688. }
  24689. this._shadowsEnabled = value;
  24690. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24696. get: function () {
  24697. return this._lightsEnabled;
  24698. },
  24699. /**
  24700. * Gets or sets a boolean indicating if lights are enabled on this scene
  24701. */
  24702. set: function (value) {
  24703. if (this._lightsEnabled === value) {
  24704. return;
  24705. }
  24706. this._lightsEnabled = value;
  24707. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24713. /** The default material used on meshes when no material is affected */
  24714. get: function () {
  24715. if (!this._defaultMaterial) {
  24716. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24717. }
  24718. return this._defaultMaterial;
  24719. },
  24720. /** The default material used on meshes when no material is affected */
  24721. set: function (value) {
  24722. this._defaultMaterial = value;
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24728. get: function () {
  24729. return this._texturesEnabled;
  24730. },
  24731. /**
  24732. * Gets or sets a boolean indicating if textures are enabled on this scene
  24733. */
  24734. set: function (value) {
  24735. if (this._texturesEnabled === value) {
  24736. return;
  24737. }
  24738. this._texturesEnabled = value;
  24739. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24745. get: function () {
  24746. return this._skeletonsEnabled;
  24747. },
  24748. /**
  24749. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24750. */
  24751. set: function (value) {
  24752. if (this._skeletonsEnabled === value) {
  24753. return;
  24754. }
  24755. this._skeletonsEnabled = value;
  24756. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24762. /**
  24763. * Gets the main soundtrack associated with the scene
  24764. */
  24765. get: function () {
  24766. if (!this._mainSoundTrack) {
  24767. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24768. }
  24769. return this._mainSoundTrack;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24775. /** @hidden */
  24776. get: function () {
  24777. return this._alternateRendering;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24783. /**
  24784. * Gets the list of frustum planes (built from the active camera)
  24785. */
  24786. get: function () {
  24787. return this._frustumPlanes;
  24788. },
  24789. enumerable: true,
  24790. configurable: true
  24791. });
  24792. /**
  24793. * Registers the transient components if needed.
  24794. */
  24795. Scene.prototype._registerTransientComponents = function () {
  24796. // Register components that have been associated lately to the scene.
  24797. if (this._transientComponents.length > 0) {
  24798. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24799. var component = _a[_i];
  24800. component.register();
  24801. }
  24802. this._transientComponents = [];
  24803. }
  24804. };
  24805. /**
  24806. * @hidden
  24807. * Add a component to the scene.
  24808. * Note that the ccomponent could be registered on th next frame if this is called after
  24809. * the register component stage.
  24810. * @param component Defines the component to add to the scene
  24811. */
  24812. Scene.prototype._addComponent = function (component) {
  24813. this._components.push(component);
  24814. this._transientComponents.push(component);
  24815. var serializableComponent = component;
  24816. if (serializableComponent.addFromContainer) {
  24817. this._serializableComponents.push(serializableComponent);
  24818. }
  24819. };
  24820. /**
  24821. * @hidden
  24822. * Gets a component from the scene.
  24823. * @param name defines the name of the component to retrieve
  24824. * @returns the component or null if not present
  24825. */
  24826. Scene.prototype._getComponent = function (name) {
  24827. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24828. var component = _a[_i];
  24829. if (component.name === name) {
  24830. return component;
  24831. }
  24832. }
  24833. return null;
  24834. };
  24835. Object.defineProperty(Scene.prototype, "debugLayer", {
  24836. /**
  24837. * Gets the debug layer (aka Inspector) associated with the scene
  24838. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24839. */
  24840. get: function () {
  24841. if (!this._debugLayer) {
  24842. this._debugLayer = new BABYLON.DebugLayer(this);
  24843. }
  24844. return this._debugLayer;
  24845. },
  24846. enumerable: true,
  24847. configurable: true
  24848. });
  24849. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24850. /**
  24851. * Gets a boolean indicating if collisions are processed on a web worker
  24852. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24853. */
  24854. get: function () {
  24855. return this._workerCollisions;
  24856. },
  24857. set: function (enabled) {
  24858. if (!BABYLON.CollisionCoordinatorLegacy) {
  24859. return;
  24860. }
  24861. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24862. this._workerCollisions = enabled;
  24863. if (this.collisionCoordinator) {
  24864. this.collisionCoordinator.destroy();
  24865. }
  24866. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24867. this.collisionCoordinator.init(this);
  24868. },
  24869. enumerable: true,
  24870. configurable: true
  24871. });
  24872. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24873. /**
  24874. * Gets the octree used to boost mesh selection (picking)
  24875. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24876. */
  24877. get: function () {
  24878. return this._selectionOctree;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24884. /**
  24885. * Gets the mesh that is currently under the pointer
  24886. */
  24887. get: function () {
  24888. return this._pointerOverMesh;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. Object.defineProperty(Scene.prototype, "pointerX", {
  24894. /**
  24895. * Gets the current on-screen X position of the pointer
  24896. */
  24897. get: function () {
  24898. return this._pointerX;
  24899. },
  24900. enumerable: true,
  24901. configurable: true
  24902. });
  24903. Object.defineProperty(Scene.prototype, "pointerY", {
  24904. /**
  24905. * Gets the current on-screen Y position of the pointer
  24906. */
  24907. get: function () {
  24908. return this._pointerY;
  24909. },
  24910. enumerable: true,
  24911. configurable: true
  24912. });
  24913. /**
  24914. * Gets the cached material (ie. the latest rendered one)
  24915. * @returns the cached material
  24916. */
  24917. Scene.prototype.getCachedMaterial = function () {
  24918. return this._cachedMaterial;
  24919. };
  24920. /**
  24921. * Gets the cached effect (ie. the latest rendered one)
  24922. * @returns the cached effect
  24923. */
  24924. Scene.prototype.getCachedEffect = function () {
  24925. return this._cachedEffect;
  24926. };
  24927. /**
  24928. * Gets the cached visibility state (ie. the latest rendered one)
  24929. * @returns the cached visibility state
  24930. */
  24931. Scene.prototype.getCachedVisibility = function () {
  24932. return this._cachedVisibility;
  24933. };
  24934. /**
  24935. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24936. * @param material defines the current material
  24937. * @param effect defines the current effect
  24938. * @param visibility defines the current visibility state
  24939. * @returns true if one parameter is not cached
  24940. */
  24941. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24942. if (visibility === void 0) { visibility = 1; }
  24943. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24944. };
  24945. /**
  24946. * Gets the outline renderer associated with the scene
  24947. * @returns a OutlineRenderer
  24948. */
  24949. Scene.prototype.getOutlineRenderer = function () {
  24950. return this._outlineRenderer;
  24951. };
  24952. /**
  24953. * Gets the engine associated with the scene
  24954. * @returns an Engine
  24955. */
  24956. Scene.prototype.getEngine = function () {
  24957. return this._engine;
  24958. };
  24959. /**
  24960. * Gets the total number of vertices rendered per frame
  24961. * @returns the total number of vertices rendered per frame
  24962. */
  24963. Scene.prototype.getTotalVertices = function () {
  24964. return this._totalVertices.current;
  24965. };
  24966. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24967. /**
  24968. * Gets the performance counter for total vertices
  24969. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24970. */
  24971. get: function () {
  24972. return this._totalVertices;
  24973. },
  24974. enumerable: true,
  24975. configurable: true
  24976. });
  24977. /**
  24978. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24979. * @returns the total number of active indices rendered per frame
  24980. */
  24981. Scene.prototype.getActiveIndices = function () {
  24982. return this._activeIndices.current;
  24983. };
  24984. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24985. /**
  24986. * Gets the performance counter for active indices
  24987. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24988. */
  24989. get: function () {
  24990. return this._activeIndices;
  24991. },
  24992. enumerable: true,
  24993. configurable: true
  24994. });
  24995. /**
  24996. * Gets the total number of active particles rendered per frame
  24997. * @returns the total number of active particles rendered per frame
  24998. */
  24999. Scene.prototype.getActiveParticles = function () {
  25000. return this._activeParticles.current;
  25001. };
  25002. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25003. /**
  25004. * Gets the performance counter for active particles
  25005. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25006. */
  25007. get: function () {
  25008. return this._activeParticles;
  25009. },
  25010. enumerable: true,
  25011. configurable: true
  25012. });
  25013. /**
  25014. * Gets the total number of active bones rendered per frame
  25015. * @returns the total number of active bones rendered per frame
  25016. */
  25017. Scene.prototype.getActiveBones = function () {
  25018. return this._activeBones.current;
  25019. };
  25020. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25021. /**
  25022. * Gets the performance counter for active bones
  25023. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25024. */
  25025. get: function () {
  25026. return this._activeBones;
  25027. },
  25028. enumerable: true,
  25029. configurable: true
  25030. });
  25031. /** @hidden */
  25032. Scene.prototype.getInterFramePerfCounter = function () {
  25033. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25034. return 0;
  25035. };
  25036. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25037. /** @hidden */
  25038. get: function () {
  25039. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25040. return null;
  25041. },
  25042. enumerable: true,
  25043. configurable: true
  25044. });
  25045. /** @hidden */
  25046. Scene.prototype.getLastFrameDuration = function () {
  25047. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25048. return 0;
  25049. };
  25050. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25051. /** @hidden */
  25052. get: function () {
  25053. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25054. return null;
  25055. },
  25056. enumerable: true,
  25057. configurable: true
  25058. });
  25059. /** @hidden */
  25060. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25061. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25062. return 0;
  25063. };
  25064. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25065. /** @hidden */
  25066. get: function () {
  25067. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25068. return null;
  25069. },
  25070. enumerable: true,
  25071. configurable: true
  25072. });
  25073. /**
  25074. * Gets the array of active meshes
  25075. * @returns an array of AbstractMesh
  25076. */
  25077. Scene.prototype.getActiveMeshes = function () {
  25078. return this._activeMeshes;
  25079. };
  25080. /** @hidden */
  25081. Scene.prototype.getRenderTargetsDuration = function () {
  25082. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25083. return 0;
  25084. };
  25085. /** @hidden */
  25086. Scene.prototype.getRenderDuration = function () {
  25087. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25088. return 0;
  25089. };
  25090. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25091. /** @hidden */
  25092. get: function () {
  25093. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25094. return null;
  25095. },
  25096. enumerable: true,
  25097. configurable: true
  25098. });
  25099. /** @hidden */
  25100. Scene.prototype.getParticlesDuration = function () {
  25101. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25102. return 0;
  25103. };
  25104. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25105. /** @hidden */
  25106. get: function () {
  25107. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25108. return null;
  25109. },
  25110. enumerable: true,
  25111. configurable: true
  25112. });
  25113. /** @hidden */
  25114. Scene.prototype.getSpritesDuration = function () {
  25115. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25116. return 0;
  25117. };
  25118. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25119. /** @hidden */
  25120. get: function () {
  25121. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25122. return null;
  25123. },
  25124. enumerable: true,
  25125. configurable: true
  25126. });
  25127. /**
  25128. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25129. * @returns a number
  25130. */
  25131. Scene.prototype.getAnimationRatio = function () {
  25132. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25133. };
  25134. /**
  25135. * Gets an unique Id for the current frame
  25136. * @returns a number
  25137. */
  25138. Scene.prototype.getRenderId = function () {
  25139. return this._renderId;
  25140. };
  25141. /** Call this function if you want to manually increment the render Id*/
  25142. Scene.prototype.incrementRenderId = function () {
  25143. this._renderId++;
  25144. };
  25145. Scene.prototype._updatePointerPosition = function (evt) {
  25146. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25147. if (!canvasRect) {
  25148. return;
  25149. }
  25150. this._pointerX = evt.clientX - canvasRect.left;
  25151. this._pointerY = evt.clientY - canvasRect.top;
  25152. this._unTranslatedPointerX = this._pointerX;
  25153. this._unTranslatedPointerY = this._pointerY;
  25154. };
  25155. Scene.prototype._createUbo = function () {
  25156. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25157. this._sceneUbo.addUniform("viewProjection", 16);
  25158. this._sceneUbo.addUniform("view", 16);
  25159. };
  25160. Scene.prototype._createAlternateUbo = function () {
  25161. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25162. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25163. this._alternateSceneUbo.addUniform("view", 16);
  25164. };
  25165. // Pointers handling
  25166. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25167. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25168. if (result) {
  25169. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25170. }
  25171. return result;
  25172. };
  25173. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25174. if (pointerInfo.pickInfo) {
  25175. if (!pointerInfo.pickInfo.ray) {
  25176. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25177. }
  25178. }
  25179. };
  25180. /**
  25181. * Use this method to simulate a pointer move on a mesh
  25182. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25183. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25184. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25185. * @returns the current scene
  25186. */
  25187. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25188. var evt = new PointerEvent("pointermove", pointerEventInit);
  25189. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25190. return this;
  25191. }
  25192. return this._processPointerMove(pickResult, evt);
  25193. };
  25194. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25195. var canvas = this._engine.getRenderingCanvas();
  25196. if (!canvas) {
  25197. return this;
  25198. }
  25199. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25200. this.setPointerOverSprite(null);
  25201. this.setPointerOverMesh(pickResult.pickedMesh);
  25202. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25203. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25204. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25205. }
  25206. else {
  25207. canvas.style.cursor = this.hoverCursor;
  25208. }
  25209. }
  25210. else {
  25211. canvas.style.cursor = this.defaultCursor;
  25212. }
  25213. }
  25214. else {
  25215. this.setPointerOverMesh(null);
  25216. // Sprites
  25217. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25218. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25219. this.setPointerOverSprite(pickResult.pickedSprite);
  25220. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25221. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25222. }
  25223. else {
  25224. canvas.style.cursor = this.hoverCursor;
  25225. }
  25226. }
  25227. else {
  25228. this.setPointerOverSprite(null);
  25229. // Restore pointer
  25230. canvas.style.cursor = this.defaultCursor;
  25231. }
  25232. }
  25233. if (pickResult) {
  25234. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25235. if (this.onPointerMove) {
  25236. this.onPointerMove(evt, pickResult, type);
  25237. }
  25238. if (this.onPointerObservable.hasObservers()) {
  25239. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25240. this._setRayOnPointerInfo(pi);
  25241. this.onPointerObservable.notifyObservers(pi, type);
  25242. }
  25243. }
  25244. return this;
  25245. };
  25246. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25247. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25248. if (pickResult) {
  25249. pi.ray = pickResult.ray;
  25250. }
  25251. this.onPrePointerObservable.notifyObservers(pi, type);
  25252. if (pi.skipOnPointerObservable) {
  25253. return true;
  25254. }
  25255. else {
  25256. return false;
  25257. }
  25258. };
  25259. /**
  25260. * Use this method to simulate a pointer down on a mesh
  25261. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25262. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25263. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25264. * @returns the current scene
  25265. */
  25266. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25267. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25268. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25269. return this;
  25270. }
  25271. return this._processPointerDown(pickResult, evt);
  25272. };
  25273. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25274. var _this = this;
  25275. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25276. this._pickedDownMesh = pickResult.pickedMesh;
  25277. var actionManager = pickResult.pickedMesh.actionManager;
  25278. if (actionManager) {
  25279. if (actionManager.hasPickTriggers) {
  25280. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25281. switch (evt.button) {
  25282. case 0:
  25283. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25284. break;
  25285. case 1:
  25286. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25287. break;
  25288. case 2:
  25289. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25290. break;
  25291. }
  25292. }
  25293. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25294. window.setTimeout(function () {
  25295. 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);
  25296. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25297. if (_this._totalPointersPressed !== 0 &&
  25298. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25299. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25300. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25301. _this._startingPointerTime = 0;
  25302. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25303. }
  25304. }
  25305. }, Scene.LongPressDelay);
  25306. }
  25307. }
  25308. }
  25309. if (pickResult) {
  25310. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25311. if (this.onPointerDown) {
  25312. this.onPointerDown(evt, pickResult, type);
  25313. }
  25314. if (this.onPointerObservable.hasObservers()) {
  25315. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25316. this._setRayOnPointerInfo(pi);
  25317. this.onPointerObservable.notifyObservers(pi, type);
  25318. }
  25319. }
  25320. return this;
  25321. };
  25322. /**
  25323. * Use this method to simulate a pointer up on a mesh
  25324. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25325. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25326. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25327. * @returns the current scene
  25328. */
  25329. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25330. var evt = new PointerEvent("pointerup", pointerEventInit);
  25331. var clickInfo = new ClickInfo();
  25332. clickInfo.singleClick = true;
  25333. clickInfo.ignore = true;
  25334. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25335. return this;
  25336. }
  25337. return this._processPointerUp(pickResult, evt, clickInfo);
  25338. };
  25339. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25340. if (pickResult && pickResult && pickResult.pickedMesh) {
  25341. this._pickedUpMesh = pickResult.pickedMesh;
  25342. if (this._pickedDownMesh === this._pickedUpMesh) {
  25343. if (this.onPointerPick) {
  25344. this.onPointerPick(evt, pickResult);
  25345. }
  25346. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25347. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25348. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25349. this._setRayOnPointerInfo(pi);
  25350. this.onPointerObservable.notifyObservers(pi, type_1);
  25351. }
  25352. }
  25353. if (pickResult.pickedMesh.actionManager) {
  25354. if (clickInfo.ignore) {
  25355. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25356. }
  25357. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25359. }
  25360. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25361. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25362. }
  25363. }
  25364. }
  25365. if (this._pickedDownMesh &&
  25366. this._pickedDownMesh.actionManager &&
  25367. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25368. this._pickedDownMesh !== this._pickedUpMesh) {
  25369. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25370. }
  25371. var type = BABYLON.PointerEventTypes.POINTERUP;
  25372. if (this.onPointerObservable.hasObservers()) {
  25373. if (!clickInfo.ignore) {
  25374. if (!clickInfo.hasSwiped) {
  25375. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25376. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25377. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25378. this._setRayOnPointerInfo(pi);
  25379. this.onPointerObservable.notifyObservers(pi, type_2);
  25380. }
  25381. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25382. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25383. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25384. this._setRayOnPointerInfo(pi);
  25385. this.onPointerObservable.notifyObservers(pi, type_3);
  25386. }
  25387. }
  25388. }
  25389. else {
  25390. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25391. this._setRayOnPointerInfo(pi);
  25392. this.onPointerObservable.notifyObservers(pi, type);
  25393. }
  25394. }
  25395. if (this.onPointerUp) {
  25396. this.onPointerUp(evt, pickResult, type);
  25397. }
  25398. return this;
  25399. };
  25400. /**
  25401. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25402. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25403. * @returns true if the pointer was captured
  25404. */
  25405. Scene.prototype.isPointerCaptured = function (pointerId) {
  25406. if (pointerId === void 0) { pointerId = 0; }
  25407. return this._pointerCaptures[pointerId];
  25408. };
  25409. /**
  25410. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25411. * @param attachUp defines if you want to attach events to pointerup
  25412. * @param attachDown defines if you want to attach events to pointerdown
  25413. * @param attachMove defines if you want to attach events to pointermove
  25414. */
  25415. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25416. var _this = this;
  25417. if (attachUp === void 0) { attachUp = true; }
  25418. if (attachDown === void 0) { attachDown = true; }
  25419. if (attachMove === void 0) { attachMove = true; }
  25420. this._initActionManager = function (act, clickInfo) {
  25421. if (!_this._meshPickProceed) {
  25422. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25423. _this._currentPickResult = pickResult;
  25424. if (pickResult) {
  25425. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25426. }
  25427. _this._meshPickProceed = true;
  25428. }
  25429. return act;
  25430. };
  25431. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25432. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25433. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25434. btn !== _this._previousButtonPressed) {
  25435. _this._doubleClickOccured = false;
  25436. clickInfo.singleClick = true;
  25437. clickInfo.ignore = false;
  25438. cb(clickInfo, _this._currentPickResult);
  25439. }
  25440. };
  25441. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25442. var clickInfo = new ClickInfo();
  25443. _this._currentPickResult = null;
  25444. var act = null;
  25445. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25446. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25447. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25448. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25449. act = _this._initActionManager(act, clickInfo);
  25450. if (act)
  25451. checkPicking = act.hasPickTriggers;
  25452. }
  25453. if (checkPicking) {
  25454. var btn = evt.button;
  25455. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25456. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25457. if (!clickInfo.hasSwiped) {
  25458. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25459. if (!checkSingleClickImmediately) {
  25460. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25461. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25462. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25463. act = _this._initActionManager(act, clickInfo);
  25464. if (act)
  25465. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25466. }
  25467. }
  25468. if (checkSingleClickImmediately) {
  25469. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25470. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25471. btn !== _this._previousButtonPressed) {
  25472. clickInfo.singleClick = true;
  25473. cb(clickInfo, _this._currentPickResult);
  25474. }
  25475. }
  25476. // at least one double click is required to be check and exclusive double click is enabled
  25477. else {
  25478. // wait that no double click has been raised during the double click delay
  25479. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25480. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25481. }
  25482. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25483. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25484. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25485. act = _this._initActionManager(act, clickInfo);
  25486. if (act)
  25487. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25488. }
  25489. if (checkDoubleClick) {
  25490. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25491. if (btn === _this._previousButtonPressed &&
  25492. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25493. !_this._doubleClickOccured) {
  25494. // pointer has not moved for 2 clicks, it's a double click
  25495. if (!clickInfo.hasSwiped &&
  25496. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25497. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25498. _this._previousStartingPointerTime = 0;
  25499. _this._doubleClickOccured = true;
  25500. clickInfo.doubleClick = true;
  25501. clickInfo.ignore = false;
  25502. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25503. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25504. }
  25505. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25506. cb(clickInfo, _this._currentPickResult);
  25507. }
  25508. // if the two successive clicks are too far, it's just two simple clicks
  25509. else {
  25510. _this._doubleClickOccured = false;
  25511. _this._previousStartingPointerTime = _this._startingPointerTime;
  25512. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25513. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25514. _this._previousButtonPressed = btn;
  25515. if (Scene.ExclusiveDoubleClickMode) {
  25516. if (_this._previousDelayedSimpleClickTimeout) {
  25517. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25518. }
  25519. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25520. cb(clickInfo, _this._previousPickResult);
  25521. }
  25522. else {
  25523. cb(clickInfo, _this._currentPickResult);
  25524. }
  25525. }
  25526. }
  25527. // just the first click of the double has been raised
  25528. else {
  25529. _this._doubleClickOccured = false;
  25530. _this._previousStartingPointerTime = _this._startingPointerTime;
  25531. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25532. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25533. _this._previousButtonPressed = btn;
  25534. }
  25535. }
  25536. }
  25537. }
  25538. clickInfo.ignore = true;
  25539. cb(clickInfo, _this._currentPickResult);
  25540. };
  25541. this._spritePredicate = function (sprite) {
  25542. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25543. };
  25544. this._onPointerMove = function (evt) {
  25545. _this._updatePointerPosition(evt);
  25546. // PreObservable support
  25547. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25548. return;
  25549. }
  25550. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25551. return;
  25552. }
  25553. if (!_this.pointerMovePredicate) {
  25554. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25555. }
  25556. // Meshes
  25557. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25558. _this._processPointerMove(pickResult, evt);
  25559. };
  25560. this._onPointerDown = function (evt) {
  25561. _this._totalPointersPressed++;
  25562. _this._pickedDownMesh = null;
  25563. _this._meshPickProceed = false;
  25564. _this._updatePointerPosition(evt);
  25565. if (_this.preventDefaultOnPointerDown && canvas) {
  25566. evt.preventDefault();
  25567. canvas.focus();
  25568. }
  25569. // PreObservable support
  25570. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25571. return;
  25572. }
  25573. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25574. return;
  25575. }
  25576. _this._pointerCaptures[evt.pointerId] = true;
  25577. _this._startingPointerPosition.x = _this._pointerX;
  25578. _this._startingPointerPosition.y = _this._pointerY;
  25579. _this._startingPointerTime = Date.now();
  25580. if (!_this.pointerDownPredicate) {
  25581. _this.pointerDownPredicate = function (mesh) {
  25582. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25583. };
  25584. }
  25585. // Meshes
  25586. _this._pickedDownMesh = null;
  25587. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25588. _this._processPointerDown(pickResult, evt);
  25589. // Sprites
  25590. _this._pickedDownSprite = null;
  25591. if (_this.spriteManagers.length > 0) {
  25592. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25593. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25594. if (pickResult.pickedSprite.actionManager) {
  25595. _this._pickedDownSprite = pickResult.pickedSprite;
  25596. switch (evt.button) {
  25597. case 0:
  25598. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25599. break;
  25600. case 1:
  25601. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25602. break;
  25603. case 2:
  25604. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25605. break;
  25606. }
  25607. if (pickResult.pickedSprite.actionManager) {
  25608. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25609. }
  25610. }
  25611. }
  25612. }
  25613. };
  25614. this._onPointerUp = function (evt) {
  25615. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25616. return; // So we need to test it the pointer down was pressed before.
  25617. }
  25618. _this._totalPointersPressed--;
  25619. _this._pickedUpMesh = null;
  25620. _this._meshPickProceed = false;
  25621. _this._updatePointerPosition(evt);
  25622. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25623. // PreObservable support
  25624. if (_this.onPrePointerObservable.hasObservers()) {
  25625. if (!clickInfo.ignore) {
  25626. if (!clickInfo.hasSwiped) {
  25627. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25628. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25629. return;
  25630. }
  25631. }
  25632. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25633. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25634. return;
  25635. }
  25636. }
  25637. }
  25638. }
  25639. else {
  25640. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25641. return;
  25642. }
  25643. }
  25644. }
  25645. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25646. return;
  25647. }
  25648. _this._pointerCaptures[evt.pointerId] = false;
  25649. if (!_this.pointerUpPredicate) {
  25650. _this.pointerUpPredicate = function (mesh) {
  25651. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25652. };
  25653. }
  25654. // Meshes
  25655. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25656. _this._initActionManager(null, clickInfo);
  25657. }
  25658. if (!pickResult) {
  25659. pickResult = _this._currentPickResult;
  25660. }
  25661. _this._processPointerUp(pickResult, evt, clickInfo);
  25662. // Sprites
  25663. if (!clickInfo.ignore) {
  25664. if (_this.spriteManagers.length > 0) {
  25665. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25666. if (spritePickResult) {
  25667. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25668. if (spritePickResult.pickedSprite.actionManager) {
  25669. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25670. if (spritePickResult.pickedSprite.actionManager) {
  25671. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25672. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25673. }
  25674. }
  25675. }
  25676. }
  25677. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25678. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25679. }
  25680. }
  25681. }
  25682. }
  25683. _this._previousPickResult = _this._currentPickResult;
  25684. });
  25685. };
  25686. this._onKeyDown = function (evt) {
  25687. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25688. if (_this.onPreKeyboardObservable.hasObservers()) {
  25689. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25690. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25691. if (pi.skipOnPointerObservable) {
  25692. return;
  25693. }
  25694. }
  25695. if (_this.onKeyboardObservable.hasObservers()) {
  25696. var pi = new BABYLON.KeyboardInfo(type, evt);
  25697. _this.onKeyboardObservable.notifyObservers(pi, type);
  25698. }
  25699. if (_this.actionManager) {
  25700. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25701. }
  25702. };
  25703. this._onKeyUp = function (evt) {
  25704. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25705. if (_this.onPreKeyboardObservable.hasObservers()) {
  25706. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25707. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25708. if (pi.skipOnPointerObservable) {
  25709. return;
  25710. }
  25711. }
  25712. if (_this.onKeyboardObservable.hasObservers()) {
  25713. var pi = new BABYLON.KeyboardInfo(type, evt);
  25714. _this.onKeyboardObservable.notifyObservers(pi, type);
  25715. }
  25716. if (_this.actionManager) {
  25717. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25718. }
  25719. };
  25720. var engine = this.getEngine();
  25721. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25722. if (!canvas) {
  25723. return;
  25724. }
  25725. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25726. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25727. });
  25728. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25729. if (!canvas) {
  25730. return;
  25731. }
  25732. canvas.removeEventListener("keydown", _this._onKeyDown);
  25733. canvas.removeEventListener("keyup", _this._onKeyUp);
  25734. });
  25735. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25736. var canvas = this._engine.getRenderingCanvas();
  25737. if (!canvas) {
  25738. return;
  25739. }
  25740. if (attachMove) {
  25741. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25742. // Wheel
  25743. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25744. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25745. }
  25746. if (attachDown) {
  25747. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25748. }
  25749. if (attachUp) {
  25750. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25751. }
  25752. canvas.tabIndex = 1;
  25753. };
  25754. /** Detaches all event handlers*/
  25755. Scene.prototype.detachControl = function () {
  25756. var engine = this.getEngine();
  25757. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25758. var canvas = engine.getRenderingCanvas();
  25759. if (!canvas) {
  25760. return;
  25761. }
  25762. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25763. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25764. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25765. if (this._onCanvasBlurObserver) {
  25766. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25767. }
  25768. if (this._onCanvasFocusObserver) {
  25769. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25770. }
  25771. // Wheel
  25772. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25773. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25774. // Keyboard
  25775. canvas.removeEventListener("keydown", this._onKeyDown);
  25776. canvas.removeEventListener("keyup", this._onKeyUp);
  25777. // Observables
  25778. this.onKeyboardObservable.clear();
  25779. this.onPreKeyboardObservable.clear();
  25780. this.onPointerObservable.clear();
  25781. this.onPrePointerObservable.clear();
  25782. };
  25783. /**
  25784. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25785. * Delay loaded resources are not taking in account
  25786. * @return true if all required resources are ready
  25787. */
  25788. Scene.prototype.isReady = function () {
  25789. if (this._isDisposed) {
  25790. return false;
  25791. }
  25792. if (this._pendingData.length > 0) {
  25793. return false;
  25794. }
  25795. var index;
  25796. var engine = this.getEngine();
  25797. // Geometries
  25798. for (index = 0; index < this.geometries.length; index++) {
  25799. var geometry = this.geometries[index];
  25800. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25801. return false;
  25802. }
  25803. }
  25804. // Meshes
  25805. for (index = 0; index < this.meshes.length; index++) {
  25806. var mesh = this.meshes[index];
  25807. if (!mesh.isEnabled()) {
  25808. continue;
  25809. }
  25810. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25811. continue;
  25812. }
  25813. if (!mesh.isReady(true)) {
  25814. return false;
  25815. }
  25816. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25817. // Is Ready For Mesh
  25818. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25819. var step = _a[_i];
  25820. if (!step.action(mesh, hardwareInstancedRendering)) {
  25821. return false;
  25822. }
  25823. }
  25824. }
  25825. // Post-processes
  25826. if (this.activeCameras && this.activeCameras.length > 0) {
  25827. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25828. var camera = _c[_b];
  25829. if (!camera.isReady(true)) {
  25830. return false;
  25831. }
  25832. }
  25833. }
  25834. else if (this.activeCamera) {
  25835. if (!this.activeCamera.isReady(true)) {
  25836. return false;
  25837. }
  25838. }
  25839. // Particles
  25840. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25841. var particleSystem = _e[_d];
  25842. if (!particleSystem.isReady()) {
  25843. return false;
  25844. }
  25845. }
  25846. return true;
  25847. };
  25848. /** Resets all cached information relative to material (including effect and visibility) */
  25849. Scene.prototype.resetCachedMaterial = function () {
  25850. this._cachedMaterial = null;
  25851. this._cachedEffect = null;
  25852. this._cachedVisibility = null;
  25853. };
  25854. /**
  25855. * Registers a function to be called before every frame render
  25856. * @param func defines the function to register
  25857. */
  25858. Scene.prototype.registerBeforeRender = function (func) {
  25859. this.onBeforeRenderObservable.add(func);
  25860. };
  25861. /**
  25862. * Unregisters a function called before every frame render
  25863. * @param func defines the function to unregister
  25864. */
  25865. Scene.prototype.unregisterBeforeRender = function (func) {
  25866. this.onBeforeRenderObservable.removeCallback(func);
  25867. };
  25868. /**
  25869. * Registers a function to be called after every frame render
  25870. * @param func defines the function to register
  25871. */
  25872. Scene.prototype.registerAfterRender = function (func) {
  25873. this.onAfterRenderObservable.add(func);
  25874. };
  25875. /**
  25876. * Unregisters a function called after every frame render
  25877. * @param func defines the function to unregister
  25878. */
  25879. Scene.prototype.unregisterAfterRender = function (func) {
  25880. this.onAfterRenderObservable.removeCallback(func);
  25881. };
  25882. Scene.prototype._executeOnceBeforeRender = function (func) {
  25883. var _this = this;
  25884. var execFunc = function () {
  25885. func();
  25886. setTimeout(function () {
  25887. _this.unregisterBeforeRender(execFunc);
  25888. });
  25889. };
  25890. this.registerBeforeRender(execFunc);
  25891. };
  25892. /**
  25893. * The provided function will run before render once and will be disposed afterwards.
  25894. * A timeout delay can be provided so that the function will be executed in N ms.
  25895. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25896. * @param func The function to be executed.
  25897. * @param timeout optional delay in ms
  25898. */
  25899. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25900. var _this = this;
  25901. if (timeout !== undefined) {
  25902. setTimeout(function () {
  25903. _this._executeOnceBeforeRender(func);
  25904. }, timeout);
  25905. }
  25906. else {
  25907. this._executeOnceBeforeRender(func);
  25908. }
  25909. };
  25910. /** @hidden */
  25911. Scene.prototype._addPendingData = function (data) {
  25912. this._pendingData.push(data);
  25913. };
  25914. /** @hidden */
  25915. Scene.prototype._removePendingData = function (data) {
  25916. var wasLoading = this.isLoading;
  25917. var index = this._pendingData.indexOf(data);
  25918. if (index !== -1) {
  25919. this._pendingData.splice(index, 1);
  25920. }
  25921. if (wasLoading && !this.isLoading) {
  25922. this.onDataLoadedObservable.notifyObservers(this);
  25923. }
  25924. };
  25925. /**
  25926. * Returns the number of items waiting to be loaded
  25927. * @returns the number of items waiting to be loaded
  25928. */
  25929. Scene.prototype.getWaitingItemsCount = function () {
  25930. return this._pendingData.length;
  25931. };
  25932. Object.defineProperty(Scene.prototype, "isLoading", {
  25933. /**
  25934. * Returns a boolean indicating if the scene is still loading data
  25935. */
  25936. get: function () {
  25937. return this._pendingData.length > 0;
  25938. },
  25939. enumerable: true,
  25940. configurable: true
  25941. });
  25942. /**
  25943. * Registers a function to be executed when the scene is ready
  25944. * @param {Function} func - the function to be executed
  25945. */
  25946. Scene.prototype.executeWhenReady = function (func) {
  25947. var _this = this;
  25948. this.onReadyObservable.add(func);
  25949. if (this._executeWhenReadyTimeoutId !== -1) {
  25950. return;
  25951. }
  25952. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25953. _this._checkIsReady();
  25954. }, 150);
  25955. };
  25956. /**
  25957. * Returns a promise that resolves when the scene is ready
  25958. * @returns A promise that resolves when the scene is ready
  25959. */
  25960. Scene.prototype.whenReadyAsync = function () {
  25961. var _this = this;
  25962. return new Promise(function (resolve) {
  25963. _this.executeWhenReady(function () {
  25964. resolve();
  25965. });
  25966. });
  25967. };
  25968. /** @hidden */
  25969. Scene.prototype._checkIsReady = function () {
  25970. var _this = this;
  25971. this._registerTransientComponents();
  25972. if (this.isReady()) {
  25973. this.onReadyObservable.notifyObservers(this);
  25974. this.onReadyObservable.clear();
  25975. this._executeWhenReadyTimeoutId = -1;
  25976. return;
  25977. }
  25978. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25979. _this._checkIsReady();
  25980. }, 150);
  25981. };
  25982. // Animations
  25983. /**
  25984. * Will start the animation sequence of a given target
  25985. * @param target defines the target
  25986. * @param from defines from which frame should animation start
  25987. * @param to defines until which frame should animation run.
  25988. * @param weight defines the weight to apply to the animation (1.0 by default)
  25989. * @param loop defines if the animation loops
  25990. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25991. * @param onAnimationEnd defines the function to be executed when the animation ends
  25992. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25993. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25994. * @returns the animatable object created for this animation
  25995. */
  25996. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25997. if (weight === void 0) { weight = 1.0; }
  25998. if (speedRatio === void 0) { speedRatio = 1.0; }
  25999. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26000. returnedAnimatable.weight = weight;
  26001. return returnedAnimatable;
  26002. };
  26003. /**
  26004. * Will start the animation sequence of a given target
  26005. * @param target defines the target
  26006. * @param from defines from which frame should animation start
  26007. * @param to defines until which frame should animation run.
  26008. * @param loop defines if the animation loops
  26009. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26010. * @param onAnimationEnd defines the function to be executed when the animation ends
  26011. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26012. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26013. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26014. * @returns the animatable object created for this animation
  26015. */
  26016. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26017. if (speedRatio === void 0) { speedRatio = 1.0; }
  26018. if (stopCurrent === void 0) { stopCurrent = true; }
  26019. if (from > to && speedRatio > 0) {
  26020. speedRatio *= -1;
  26021. }
  26022. if (stopCurrent) {
  26023. this.stopAnimation(target, undefined, targetMask);
  26024. }
  26025. if (!animatable) {
  26026. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26027. }
  26028. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26029. // Local animations
  26030. if (target.animations && shouldRunTargetAnimations) {
  26031. animatable.appendAnimations(target, target.animations);
  26032. }
  26033. // Children animations
  26034. if (target.getAnimatables) {
  26035. var animatables = target.getAnimatables();
  26036. for (var index = 0; index < animatables.length; index++) {
  26037. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26038. }
  26039. }
  26040. animatable.reset();
  26041. return animatable;
  26042. };
  26043. /**
  26044. * Begin a new animation on a given node
  26045. * @param target defines the target where the animation will take place
  26046. * @param animations defines the list of animations to start
  26047. * @param from defines the initial value
  26048. * @param to defines the final value
  26049. * @param loop defines if you want animation to loop (off by default)
  26050. * @param speedRatio defines the speed ratio to apply to all animations
  26051. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26052. * @returns the list of created animatables
  26053. */
  26054. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26055. if (speedRatio === undefined) {
  26056. speedRatio = 1.0;
  26057. }
  26058. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26059. return animatable;
  26060. };
  26061. /**
  26062. * Begin a new animation on a given node and its hierarchy
  26063. * @param target defines the root node where the animation will take place
  26064. * @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.
  26065. * @param animations defines the list of animations to start
  26066. * @param from defines the initial value
  26067. * @param to defines the final value
  26068. * @param loop defines if you want animation to loop (off by default)
  26069. * @param speedRatio defines the speed ratio to apply to all animations
  26070. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26071. * @returns the list of animatables created for all nodes
  26072. */
  26073. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26074. var children = target.getDescendants(directDescendantsOnly);
  26075. var result = [];
  26076. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26077. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26078. var child = children_1[_i];
  26079. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26080. }
  26081. return result;
  26082. };
  26083. /**
  26084. * Gets the animatable associated with a specific target
  26085. * @param target defines the target of the animatable
  26086. * @returns the required animatable if found
  26087. */
  26088. Scene.prototype.getAnimatableByTarget = function (target) {
  26089. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26090. if (this._activeAnimatables[index].target === target) {
  26091. return this._activeAnimatables[index];
  26092. }
  26093. }
  26094. return null;
  26095. };
  26096. /**
  26097. * Gets all animatables associated with a given target
  26098. * @param target defines the target to look animatables for
  26099. * @returns an array of Animatables
  26100. */
  26101. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26102. var result = [];
  26103. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26104. if (this._activeAnimatables[index].target === target) {
  26105. result.push(this._activeAnimatables[index]);
  26106. }
  26107. }
  26108. return result;
  26109. };
  26110. Object.defineProperty(Scene.prototype, "animatables", {
  26111. /**
  26112. * Gets all animatable attached to the scene
  26113. */
  26114. get: function () {
  26115. return this._activeAnimatables;
  26116. },
  26117. enumerable: true,
  26118. configurable: true
  26119. });
  26120. /**
  26121. * Will stop the animation of the given target
  26122. * @param target - the target
  26123. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26124. * @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)
  26125. */
  26126. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26127. var animatables = this.getAllAnimatablesByTarget(target);
  26128. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26129. var animatable = animatables_1[_i];
  26130. animatable.stop(animationName, targetMask);
  26131. }
  26132. };
  26133. /**
  26134. * Stops and removes all animations that have been applied to the scene
  26135. */
  26136. Scene.prototype.stopAllAnimations = function () {
  26137. if (this._activeAnimatables) {
  26138. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26139. this._activeAnimatables[i].stop();
  26140. }
  26141. this._activeAnimatables = [];
  26142. }
  26143. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26144. var group = _a[_i];
  26145. group.stop();
  26146. }
  26147. };
  26148. Scene.prototype._animate = function () {
  26149. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26150. return;
  26151. }
  26152. // Getting time
  26153. var now = BABYLON.Tools.Now;
  26154. if (!this._animationTimeLast) {
  26155. if (this._pendingData.length > 0) {
  26156. return;
  26157. }
  26158. this._animationTimeLast = now;
  26159. }
  26160. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26161. this._animationTime += deltaTime;
  26162. this._animationTimeLast = now;
  26163. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26164. this._activeAnimatables[index]._animate(this._animationTime);
  26165. }
  26166. // Late animation bindings
  26167. this._processLateAnimationBindings();
  26168. };
  26169. /** @hidden */
  26170. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26171. var target = runtimeAnimation.target;
  26172. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26173. if (!target._lateAnimationHolders) {
  26174. target._lateAnimationHolders = {};
  26175. }
  26176. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26177. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26178. totalWeight: 0,
  26179. animations: [],
  26180. originalValue: originalValue
  26181. };
  26182. }
  26183. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26184. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26185. };
  26186. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26187. var normalizer = 1.0;
  26188. var finalPosition = BABYLON.Tmp.Vector3[0];
  26189. var finalScaling = BABYLON.Tmp.Vector3[1];
  26190. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26191. var startIndex = 0;
  26192. var originalAnimation = holder.animations[0];
  26193. var originalValue = holder.originalValue;
  26194. var scale = 1;
  26195. if (holder.totalWeight < 1.0) {
  26196. // We need to mix the original value in
  26197. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26198. scale = 1.0 - holder.totalWeight;
  26199. }
  26200. else {
  26201. startIndex = 1;
  26202. // We need to normalize the weights
  26203. normalizer = holder.totalWeight;
  26204. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26205. scale = originalAnimation.weight / normalizer;
  26206. if (scale == 1) {
  26207. return originalAnimation.currentValue;
  26208. }
  26209. }
  26210. finalScaling.scaleInPlace(scale);
  26211. finalPosition.scaleInPlace(scale);
  26212. finalQuaternion.scaleInPlace(scale);
  26213. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26214. var runtimeAnimation = holder.animations[animIndex];
  26215. var scale = runtimeAnimation.weight / normalizer;
  26216. var currentPosition = BABYLON.Tmp.Vector3[2];
  26217. var currentScaling = BABYLON.Tmp.Vector3[3];
  26218. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26219. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26220. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26221. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26222. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26223. }
  26224. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26225. return originalAnimation._workValue;
  26226. };
  26227. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26228. var originalAnimation = holder.animations[0];
  26229. var originalValue = holder.originalValue;
  26230. if (holder.animations.length === 1) {
  26231. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26232. }
  26233. var normalizer = 1.0;
  26234. var quaternions;
  26235. var weights;
  26236. if (holder.totalWeight < 1.0) {
  26237. var scale = 1.0 - holder.totalWeight;
  26238. quaternions = [];
  26239. weights = [];
  26240. quaternions.push(originalValue);
  26241. weights.push(scale);
  26242. }
  26243. else {
  26244. if (holder.animations.length === 2) { // Slerp as soon as we can
  26245. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26246. }
  26247. quaternions = [];
  26248. weights = [];
  26249. normalizer = holder.totalWeight;
  26250. }
  26251. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26252. var runtimeAnimation = holder.animations[animIndex];
  26253. quaternions.push(runtimeAnimation.currentValue);
  26254. weights.push(runtimeAnimation.weight / normalizer);
  26255. }
  26256. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26257. var cumulativeAmount = 0;
  26258. var cumulativeQuaternion = null;
  26259. for (var index = 0; index < quaternions.length;) {
  26260. if (!cumulativeQuaternion) {
  26261. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26262. cumulativeAmount = weights[index] + weights[index + 1];
  26263. index += 2;
  26264. continue;
  26265. }
  26266. cumulativeAmount += weights[index];
  26267. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26268. index++;
  26269. }
  26270. return cumulativeQuaternion;
  26271. };
  26272. Scene.prototype._processLateAnimationBindings = function () {
  26273. if (!this._registeredForLateAnimationBindings.length) {
  26274. return;
  26275. }
  26276. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26277. var target = this._registeredForLateAnimationBindings.data[index];
  26278. for (var path in target._lateAnimationHolders) {
  26279. var holder = target._lateAnimationHolders[path];
  26280. var originalAnimation = holder.animations[0];
  26281. var originalValue = holder.originalValue;
  26282. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26283. var finalValue = void 0;
  26284. if (matrixDecomposeMode) {
  26285. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26286. }
  26287. else {
  26288. var quaternionMode = originalValue.w !== undefined;
  26289. if (quaternionMode) {
  26290. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26291. }
  26292. else {
  26293. var startIndex = 0;
  26294. var normalizer = 1.0;
  26295. if (holder.totalWeight < 1.0) {
  26296. // We need to mix the original value in
  26297. if (originalValue.scale) {
  26298. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26299. }
  26300. else {
  26301. finalValue = originalValue * (1.0 - holder.totalWeight);
  26302. }
  26303. }
  26304. else {
  26305. // We need to normalize the weights
  26306. normalizer = holder.totalWeight;
  26307. var scale_1 = originalAnimation.weight / normalizer;
  26308. if (scale_1 !== 1) {
  26309. if (originalAnimation.currentValue.scale) {
  26310. finalValue = originalAnimation.currentValue.scale(scale_1);
  26311. }
  26312. else {
  26313. finalValue = originalAnimation.currentValue * scale_1;
  26314. }
  26315. }
  26316. else {
  26317. finalValue = originalAnimation.currentValue;
  26318. }
  26319. startIndex = 1;
  26320. }
  26321. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26322. var runtimeAnimation = holder.animations[animIndex];
  26323. var scale = runtimeAnimation.weight / normalizer;
  26324. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26325. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26326. }
  26327. else {
  26328. finalValue += runtimeAnimation.currentValue * scale;
  26329. }
  26330. }
  26331. }
  26332. }
  26333. target[path] = finalValue;
  26334. }
  26335. target._lateAnimationHolders = {};
  26336. }
  26337. this._registeredForLateAnimationBindings.reset();
  26338. };
  26339. // Matrix
  26340. /** @hidden */
  26341. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26342. this._useAlternateCameraConfiguration = active;
  26343. };
  26344. /**
  26345. * Gets the current view matrix
  26346. * @returns a Matrix
  26347. */
  26348. Scene.prototype.getViewMatrix = function () {
  26349. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26350. };
  26351. /**
  26352. * Gets the current projection matrix
  26353. * @returns a Matrix
  26354. */
  26355. Scene.prototype.getProjectionMatrix = function () {
  26356. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26357. };
  26358. /**
  26359. * Gets the current transform matrix
  26360. * @returns a Matrix made of View * Projection
  26361. */
  26362. Scene.prototype.getTransformMatrix = function () {
  26363. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26364. };
  26365. /**
  26366. * Sets the current transform matrix
  26367. * @param view defines the View matrix to use
  26368. * @param projection defines the Projection matrix to use
  26369. */
  26370. Scene.prototype.setTransformMatrix = function (view, projection) {
  26371. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26372. return;
  26373. }
  26374. this._viewUpdateFlag = view.updateFlag;
  26375. this._projectionUpdateFlag = projection.updateFlag;
  26376. this._viewMatrix = view;
  26377. this._projectionMatrix = projection;
  26378. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26379. // Update frustum
  26380. if (!this._frustumPlanes) {
  26381. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26382. }
  26383. else {
  26384. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26385. }
  26386. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26387. var otherCamera = this.activeCamera._alternateCamera;
  26388. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26389. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26390. }
  26391. if (this._sceneUbo.useUbo) {
  26392. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26393. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26394. this._sceneUbo.update();
  26395. }
  26396. };
  26397. /** @hidden */
  26398. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26399. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26400. return;
  26401. }
  26402. this._alternateViewUpdateFlag = view.updateFlag;
  26403. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26404. this._alternateViewMatrix = view;
  26405. this._alternateProjectionMatrix = projection;
  26406. if (!this._alternateTransformMatrix) {
  26407. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26408. }
  26409. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26410. if (!this._alternateSceneUbo) {
  26411. this._createAlternateUbo();
  26412. }
  26413. if (this._alternateSceneUbo.useUbo) {
  26414. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26415. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26416. this._alternateSceneUbo.update();
  26417. }
  26418. };
  26419. /**
  26420. * Gets the uniform buffer used to store scene data
  26421. * @returns a UniformBuffer
  26422. */
  26423. Scene.prototype.getSceneUniformBuffer = function () {
  26424. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26425. };
  26426. /**
  26427. * Gets an unique (relatively to the current scene) Id
  26428. * @returns an unique number for the scene
  26429. */
  26430. Scene.prototype.getUniqueId = function () {
  26431. var result = Scene._uniqueIdCounter;
  26432. Scene._uniqueIdCounter++;
  26433. return result;
  26434. };
  26435. /**
  26436. * Add a mesh to the list of scene's meshes
  26437. * @param newMesh defines the mesh to add
  26438. * @param recursive if all child meshes should also be added to the scene
  26439. */
  26440. Scene.prototype.addMesh = function (newMesh, recursive) {
  26441. var _this = this;
  26442. if (recursive === void 0) { recursive = false; }
  26443. this.meshes.push(newMesh);
  26444. //notify the collision coordinator
  26445. if (this.collisionCoordinator) {
  26446. this.collisionCoordinator.onMeshAdded(newMesh);
  26447. }
  26448. newMesh._resyncLightSources();
  26449. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26450. if (recursive) {
  26451. newMesh.getChildMeshes().forEach(function (m) {
  26452. _this.addMesh(m);
  26453. });
  26454. }
  26455. };
  26456. /**
  26457. * Remove a mesh for the list of scene's meshes
  26458. * @param toRemove defines the mesh to remove
  26459. * @param recursive if all child meshes should also be removed from the scene
  26460. * @returns the index where the mesh was in the mesh list
  26461. */
  26462. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26463. var _this = this;
  26464. if (recursive === void 0) { recursive = false; }
  26465. var index = this.meshes.indexOf(toRemove);
  26466. if (index !== -1) {
  26467. // Remove from the scene if mesh found
  26468. this.meshes.splice(index, 1);
  26469. }
  26470. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26471. if (recursive) {
  26472. toRemove.getChildMeshes().forEach(function (m) {
  26473. _this.removeMesh(m);
  26474. });
  26475. }
  26476. return index;
  26477. };
  26478. /**
  26479. * Add a transform node to the list of scene's transform nodes
  26480. * @param newTransformNode defines the transform node to add
  26481. */
  26482. Scene.prototype.addTransformNode = function (newTransformNode) {
  26483. this.transformNodes.push(newTransformNode);
  26484. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26485. };
  26486. /**
  26487. * Remove a transform node for the list of scene's transform nodes
  26488. * @param toRemove defines the transform node to remove
  26489. * @returns the index where the transform node was in the transform node list
  26490. */
  26491. Scene.prototype.removeTransformNode = function (toRemove) {
  26492. var index = this.transformNodes.indexOf(toRemove);
  26493. if (index !== -1) {
  26494. // Remove from the scene if found
  26495. this.transformNodes.splice(index, 1);
  26496. }
  26497. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26498. return index;
  26499. };
  26500. /**
  26501. * Remove a skeleton for the list of scene's skeletons
  26502. * @param toRemove defines the skeleton to remove
  26503. * @returns the index where the skeleton was in the skeleton list
  26504. */
  26505. Scene.prototype.removeSkeleton = function (toRemove) {
  26506. var index = this.skeletons.indexOf(toRemove);
  26507. if (index !== -1) {
  26508. // Remove from the scene if found
  26509. this.skeletons.splice(index, 1);
  26510. }
  26511. return index;
  26512. };
  26513. /**
  26514. * Remove a morph target for the list of scene's morph targets
  26515. * @param toRemove defines the morph target to remove
  26516. * @returns the index where the morph target was in the morph target list
  26517. */
  26518. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26519. var index = this.morphTargetManagers.indexOf(toRemove);
  26520. if (index !== -1) {
  26521. // Remove from the scene if found
  26522. this.morphTargetManagers.splice(index, 1);
  26523. }
  26524. return index;
  26525. };
  26526. /**
  26527. * Remove a light for the list of scene's lights
  26528. * @param toRemove defines the light to remove
  26529. * @returns the index where the light was in the light list
  26530. */
  26531. Scene.prototype.removeLight = function (toRemove) {
  26532. var index = this.lights.indexOf(toRemove);
  26533. if (index !== -1) {
  26534. // Remove from meshes
  26535. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26536. var mesh = _a[_i];
  26537. mesh._removeLightSource(toRemove);
  26538. }
  26539. // Remove from the scene if mesh found
  26540. this.lights.splice(index, 1);
  26541. this.sortLightsByPriority();
  26542. }
  26543. this.onLightRemovedObservable.notifyObservers(toRemove);
  26544. return index;
  26545. };
  26546. /**
  26547. * Remove a camera for the list of scene's cameras
  26548. * @param toRemove defines the camera to remove
  26549. * @returns the index where the camera was in the camera list
  26550. */
  26551. Scene.prototype.removeCamera = function (toRemove) {
  26552. var index = this.cameras.indexOf(toRemove);
  26553. if (index !== -1) {
  26554. // Remove from the scene if mesh found
  26555. this.cameras.splice(index, 1);
  26556. }
  26557. // Remove from activeCameras
  26558. var index2 = this.activeCameras.indexOf(toRemove);
  26559. if (index2 !== -1) {
  26560. // Remove from the scene if mesh found
  26561. this.activeCameras.splice(index2, 1);
  26562. }
  26563. // Reset the activeCamera
  26564. if (this.activeCamera === toRemove) {
  26565. if (this.cameras.length > 0) {
  26566. this.activeCamera = this.cameras[0];
  26567. }
  26568. else {
  26569. this.activeCamera = null;
  26570. }
  26571. }
  26572. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26573. return index;
  26574. };
  26575. /**
  26576. * Remove a particle system for the list of scene's particle systems
  26577. * @param toRemove defines the particle system to remove
  26578. * @returns the index where the particle system was in the particle system list
  26579. */
  26580. Scene.prototype.removeParticleSystem = function (toRemove) {
  26581. var index = this.particleSystems.indexOf(toRemove);
  26582. if (index !== -1) {
  26583. this.particleSystems.splice(index, 1);
  26584. }
  26585. return index;
  26586. };
  26587. /**
  26588. * Remove a animation for the list of scene's animations
  26589. * @param toRemove defines the animation to remove
  26590. * @returns the index where the animation was in the animation list
  26591. */
  26592. Scene.prototype.removeAnimation = function (toRemove) {
  26593. var index = this.animations.indexOf(toRemove);
  26594. if (index !== -1) {
  26595. this.animations.splice(index, 1);
  26596. }
  26597. return index;
  26598. };
  26599. /**
  26600. * Removes the given animation group from this scene.
  26601. * @param toRemove The animation group to remove
  26602. * @returns The index of the removed animation group
  26603. */
  26604. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26605. var index = this.animationGroups.indexOf(toRemove);
  26606. if (index !== -1) {
  26607. this.animationGroups.splice(index, 1);
  26608. }
  26609. return index;
  26610. };
  26611. /**
  26612. * Removes the given multi-material from this scene.
  26613. * @param toRemove The multi-material to remove
  26614. * @returns The index of the removed multi-material
  26615. */
  26616. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26617. var index = this.multiMaterials.indexOf(toRemove);
  26618. if (index !== -1) {
  26619. this.multiMaterials.splice(index, 1);
  26620. }
  26621. return index;
  26622. };
  26623. /**
  26624. * Removes the given material from this scene.
  26625. * @param toRemove The material to remove
  26626. * @returns The index of the removed material
  26627. */
  26628. Scene.prototype.removeMaterial = function (toRemove) {
  26629. var index = this.materials.indexOf(toRemove);
  26630. if (index !== -1) {
  26631. this.materials.splice(index, 1);
  26632. }
  26633. return index;
  26634. };
  26635. /**
  26636. * Removes the given action manager from this scene.
  26637. * @param toRemove The action manager to remove
  26638. * @returns The index of the removed action manager
  26639. */
  26640. Scene.prototype.removeActionManager = function (toRemove) {
  26641. var index = this.actionManagers.indexOf(toRemove);
  26642. if (index !== -1) {
  26643. this.actionManagers.splice(index, 1);
  26644. }
  26645. return index;
  26646. };
  26647. /**
  26648. * Removes the given texture from this scene.
  26649. * @param toRemove The texture to remove
  26650. * @returns The index of the removed texture
  26651. */
  26652. Scene.prototype.removeTexture = function (toRemove) {
  26653. var index = this.textures.indexOf(toRemove);
  26654. if (index !== -1) {
  26655. this.textures.splice(index, 1);
  26656. }
  26657. return index;
  26658. };
  26659. /**
  26660. * Adds the given light to this scene
  26661. * @param newLight The light to add
  26662. */
  26663. Scene.prototype.addLight = function (newLight) {
  26664. this.lights.push(newLight);
  26665. this.sortLightsByPriority();
  26666. // Add light to all meshes (To support if the light is removed and then readded)
  26667. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26668. var mesh = _a[_i];
  26669. if (mesh._lightSources.indexOf(newLight) === -1) {
  26670. mesh._lightSources.push(newLight);
  26671. mesh._resyncLightSources();
  26672. }
  26673. }
  26674. this.onNewLightAddedObservable.notifyObservers(newLight);
  26675. };
  26676. /**
  26677. * Sorts the list list based on light priorities
  26678. */
  26679. Scene.prototype.sortLightsByPriority = function () {
  26680. if (this.requireLightSorting) {
  26681. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26682. }
  26683. };
  26684. /**
  26685. * Adds the given camera to this scene
  26686. * @param newCamera The camera to add
  26687. */
  26688. Scene.prototype.addCamera = function (newCamera) {
  26689. this.cameras.push(newCamera);
  26690. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26691. };
  26692. /**
  26693. * Adds the given skeleton to this scene
  26694. * @param newSkeleton The skeleton to add
  26695. */
  26696. Scene.prototype.addSkeleton = function (newSkeleton) {
  26697. this.skeletons.push(newSkeleton);
  26698. };
  26699. /**
  26700. * Adds the given particle system to this scene
  26701. * @param newParticleSystem The particle system to add
  26702. */
  26703. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26704. this.particleSystems.push(newParticleSystem);
  26705. };
  26706. /**
  26707. * Adds the given animation to this scene
  26708. * @param newAnimation The animation to add
  26709. */
  26710. Scene.prototype.addAnimation = function (newAnimation) {
  26711. this.animations.push(newAnimation);
  26712. };
  26713. /**
  26714. * Adds the given animation group to this scene.
  26715. * @param newAnimationGroup The animation group to add
  26716. */
  26717. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26718. this.animationGroups.push(newAnimationGroup);
  26719. };
  26720. /**
  26721. * Adds the given multi-material to this scene
  26722. * @param newMultiMaterial The multi-material to add
  26723. */
  26724. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26725. this.multiMaterials.push(newMultiMaterial);
  26726. };
  26727. /**
  26728. * Adds the given material to this scene
  26729. * @param newMaterial The material to add
  26730. */
  26731. Scene.prototype.addMaterial = function (newMaterial) {
  26732. this.materials.push(newMaterial);
  26733. };
  26734. /**
  26735. * Adds the given morph target to this scene
  26736. * @param newMorphTargetManager The morph target to add
  26737. */
  26738. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26739. this.morphTargetManagers.push(newMorphTargetManager);
  26740. };
  26741. /**
  26742. * Adds the given geometry to this scene
  26743. * @param newGeometry The geometry to add
  26744. */
  26745. Scene.prototype.addGeometry = function (newGeometry) {
  26746. this.geometries.push(newGeometry);
  26747. };
  26748. /**
  26749. * Adds the given action manager to this scene
  26750. * @param newActionManager The action manager to add
  26751. */
  26752. Scene.prototype.addActionManager = function (newActionManager) {
  26753. this.actionManagers.push(newActionManager);
  26754. };
  26755. /**
  26756. * Adds the given texture to this scene.
  26757. * @param newTexture The texture to add
  26758. */
  26759. Scene.prototype.addTexture = function (newTexture) {
  26760. this.textures.push(newTexture);
  26761. };
  26762. /**
  26763. * Switch active camera
  26764. * @param newCamera defines the new active camera
  26765. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26766. */
  26767. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26768. if (attachControl === void 0) { attachControl = true; }
  26769. var canvas = this._engine.getRenderingCanvas();
  26770. if (!canvas) {
  26771. return;
  26772. }
  26773. if (this.activeCamera) {
  26774. this.activeCamera.detachControl(canvas);
  26775. }
  26776. this.activeCamera = newCamera;
  26777. if (attachControl) {
  26778. newCamera.attachControl(canvas);
  26779. }
  26780. };
  26781. /**
  26782. * sets the active camera of the scene using its ID
  26783. * @param id defines the camera's ID
  26784. * @return the new active camera or null if none found.
  26785. */
  26786. Scene.prototype.setActiveCameraByID = function (id) {
  26787. var camera = this.getCameraByID(id);
  26788. if (camera) {
  26789. this.activeCamera = camera;
  26790. return camera;
  26791. }
  26792. return null;
  26793. };
  26794. /**
  26795. * sets the active camera of the scene using its name
  26796. * @param name defines the camera's name
  26797. * @returns the new active camera or null if none found.
  26798. */
  26799. Scene.prototype.setActiveCameraByName = function (name) {
  26800. var camera = this.getCameraByName(name);
  26801. if (camera) {
  26802. this.activeCamera = camera;
  26803. return camera;
  26804. }
  26805. return null;
  26806. };
  26807. /**
  26808. * get an animation group using its name
  26809. * @param name defines the material's name
  26810. * @return the animation group or null if none found.
  26811. */
  26812. Scene.prototype.getAnimationGroupByName = function (name) {
  26813. for (var index = 0; index < this.animationGroups.length; index++) {
  26814. if (this.animationGroups[index].name === name) {
  26815. return this.animationGroups[index];
  26816. }
  26817. }
  26818. return null;
  26819. };
  26820. /**
  26821. * get a material using its id
  26822. * @param id defines the material's ID
  26823. * @return the material or null if none found.
  26824. */
  26825. Scene.prototype.getMaterialByID = function (id) {
  26826. for (var index = 0; index < this.materials.length; index++) {
  26827. if (this.materials[index].id === id) {
  26828. return this.materials[index];
  26829. }
  26830. }
  26831. return null;
  26832. };
  26833. /**
  26834. * Gets a material using its name
  26835. * @param name defines the material's name
  26836. * @return the material or null if none found.
  26837. */
  26838. Scene.prototype.getMaterialByName = function (name) {
  26839. for (var index = 0; index < this.materials.length; index++) {
  26840. if (this.materials[index].name === name) {
  26841. return this.materials[index];
  26842. }
  26843. }
  26844. return null;
  26845. };
  26846. /**
  26847. * Gets a camera using its id
  26848. * @param id defines the id to look for
  26849. * @returns the camera or null if not found
  26850. */
  26851. Scene.prototype.getCameraByID = function (id) {
  26852. for (var index = 0; index < this.cameras.length; index++) {
  26853. if (this.cameras[index].id === id) {
  26854. return this.cameras[index];
  26855. }
  26856. }
  26857. return null;
  26858. };
  26859. /**
  26860. * Gets a camera using its unique id
  26861. * @param uniqueId defines the unique id to look for
  26862. * @returns the camera or null if not found
  26863. */
  26864. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26865. for (var index = 0; index < this.cameras.length; index++) {
  26866. if (this.cameras[index].uniqueId === uniqueId) {
  26867. return this.cameras[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Gets a camera using its name
  26874. * @param name defines the camera's name
  26875. * @return the camera or null if none found.
  26876. */
  26877. Scene.prototype.getCameraByName = function (name) {
  26878. for (var index = 0; index < this.cameras.length; index++) {
  26879. if (this.cameras[index].name === name) {
  26880. return this.cameras[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a bone using its id
  26887. * @param id defines the bone's id
  26888. * @return the bone or null if not found
  26889. */
  26890. Scene.prototype.getBoneByID = function (id) {
  26891. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26892. var skeleton = this.skeletons[skeletonIndex];
  26893. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26894. if (skeleton.bones[boneIndex].id === id) {
  26895. return skeleton.bones[boneIndex];
  26896. }
  26897. }
  26898. }
  26899. return null;
  26900. };
  26901. /**
  26902. * Gets a bone using its id
  26903. * @param name defines the bone's name
  26904. * @return the bone or null if not found
  26905. */
  26906. Scene.prototype.getBoneByName = function (name) {
  26907. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26908. var skeleton = this.skeletons[skeletonIndex];
  26909. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26910. if (skeleton.bones[boneIndex].name === name) {
  26911. return skeleton.bones[boneIndex];
  26912. }
  26913. }
  26914. }
  26915. return null;
  26916. };
  26917. /**
  26918. * Gets a light node using its name
  26919. * @param name defines the the light's name
  26920. * @return the light or null if none found.
  26921. */
  26922. Scene.prototype.getLightByName = function (name) {
  26923. for (var index = 0; index < this.lights.length; index++) {
  26924. if (this.lights[index].name === name) {
  26925. return this.lights[index];
  26926. }
  26927. }
  26928. return null;
  26929. };
  26930. /**
  26931. * Gets a light node using its id
  26932. * @param id defines the light's id
  26933. * @return the light or null if none found.
  26934. */
  26935. Scene.prototype.getLightByID = function (id) {
  26936. for (var index = 0; index < this.lights.length; index++) {
  26937. if (this.lights[index].id === id) {
  26938. return this.lights[index];
  26939. }
  26940. }
  26941. return null;
  26942. };
  26943. /**
  26944. * Gets a light node using its scene-generated unique ID
  26945. * @param uniqueId defines the light's unique id
  26946. * @return the light or null if none found.
  26947. */
  26948. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26949. for (var index = 0; index < this.lights.length; index++) {
  26950. if (this.lights[index].uniqueId === uniqueId) {
  26951. return this.lights[index];
  26952. }
  26953. }
  26954. return null;
  26955. };
  26956. /**
  26957. * Gets a particle system by id
  26958. * @param id defines the particle system id
  26959. * @return the corresponding system or null if none found
  26960. */
  26961. Scene.prototype.getParticleSystemByID = function (id) {
  26962. for (var index = 0; index < this.particleSystems.length; index++) {
  26963. if (this.particleSystems[index].id === id) {
  26964. return this.particleSystems[index];
  26965. }
  26966. }
  26967. return null;
  26968. };
  26969. /**
  26970. * Gets a geometry using its ID
  26971. * @param id defines the geometry's id
  26972. * @return the geometry or null if none found.
  26973. */
  26974. Scene.prototype.getGeometryByID = function (id) {
  26975. for (var index = 0; index < this.geometries.length; index++) {
  26976. if (this.geometries[index].id === id) {
  26977. return this.geometries[index];
  26978. }
  26979. }
  26980. return null;
  26981. };
  26982. /**
  26983. * Add a new geometry to this scene
  26984. * @param geometry defines the geometry to be added to the scene.
  26985. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26986. * @return a boolean defining if the geometry was added or not
  26987. */
  26988. Scene.prototype.pushGeometry = function (geometry, force) {
  26989. if (!force && this.getGeometryByID(geometry.id)) {
  26990. return false;
  26991. }
  26992. this.geometries.push(geometry);
  26993. //notify the collision coordinator
  26994. if (this.collisionCoordinator) {
  26995. this.collisionCoordinator.onGeometryAdded(geometry);
  26996. }
  26997. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26998. return true;
  26999. };
  27000. /**
  27001. * Removes an existing geometry
  27002. * @param geometry defines the geometry to be removed from the scene
  27003. * @return a boolean defining if the geometry was removed or not
  27004. */
  27005. Scene.prototype.removeGeometry = function (geometry) {
  27006. var index = this.geometries.indexOf(geometry);
  27007. if (index > -1) {
  27008. this.geometries.splice(index, 1);
  27009. //notify the collision coordinator
  27010. if (this.collisionCoordinator) {
  27011. this.collisionCoordinator.onGeometryDeleted(geometry);
  27012. }
  27013. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27014. return true;
  27015. }
  27016. return false;
  27017. };
  27018. /**
  27019. * Gets the list of geometries attached to the scene
  27020. * @returns an array of Geometry
  27021. */
  27022. Scene.prototype.getGeometries = function () {
  27023. return this.geometries;
  27024. };
  27025. /**
  27026. * Gets the first added mesh found of a given ID
  27027. * @param id defines the id to search for
  27028. * @return the mesh found or null if not found at all
  27029. */
  27030. Scene.prototype.getMeshByID = function (id) {
  27031. for (var index = 0; index < this.meshes.length; index++) {
  27032. if (this.meshes[index].id === id) {
  27033. return this.meshes[index];
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. /**
  27039. * Gets a list of meshes using their id
  27040. * @param id defines the id to search for
  27041. * @returns a list of meshes
  27042. */
  27043. Scene.prototype.getMeshesByID = function (id) {
  27044. return this.meshes.filter(function (m) {
  27045. return m.id === id;
  27046. });
  27047. };
  27048. /**
  27049. * Gets the first added transform node found of a given ID
  27050. * @param id defines the id to search for
  27051. * @return the found transform node or null if not found at all.
  27052. */
  27053. Scene.prototype.getTransformNodeByID = function (id) {
  27054. for (var index = 0; index < this.transformNodes.length; index++) {
  27055. if (this.transformNodes[index].id === id) {
  27056. return this.transformNodes[index];
  27057. }
  27058. }
  27059. return null;
  27060. };
  27061. /**
  27062. * Gets a list of transform nodes using their id
  27063. * @param id defines the id to search for
  27064. * @returns a list of transform nodes
  27065. */
  27066. Scene.prototype.getTransformNodesByID = function (id) {
  27067. return this.transformNodes.filter(function (m) {
  27068. return m.id === id;
  27069. });
  27070. };
  27071. /**
  27072. * Gets a mesh with its auto-generated unique id
  27073. * @param uniqueId defines the unique id to search for
  27074. * @return the found mesh or null if not found at all.
  27075. */
  27076. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27077. for (var index = 0; index < this.meshes.length; index++) {
  27078. if (this.meshes[index].uniqueId === uniqueId) {
  27079. return this.meshes[index];
  27080. }
  27081. }
  27082. return null;
  27083. };
  27084. /**
  27085. * Gets a the last added mesh using a given id
  27086. * @param id defines the id to search for
  27087. * @return the found mesh or null if not found at all.
  27088. */
  27089. Scene.prototype.getLastMeshByID = function (id) {
  27090. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27091. if (this.meshes[index].id === id) {
  27092. return this.meshes[index];
  27093. }
  27094. }
  27095. return null;
  27096. };
  27097. /**
  27098. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27099. * @param id defines the id to search for
  27100. * @return the found node or null if not found at all
  27101. */
  27102. Scene.prototype.getLastEntryByID = function (id) {
  27103. var index;
  27104. for (index = this.meshes.length - 1; index >= 0; index--) {
  27105. if (this.meshes[index].id === id) {
  27106. return this.meshes[index];
  27107. }
  27108. }
  27109. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27110. if (this.transformNodes[index].id === id) {
  27111. return this.transformNodes[index];
  27112. }
  27113. }
  27114. for (index = this.cameras.length - 1; index >= 0; index--) {
  27115. if (this.cameras[index].id === id) {
  27116. return this.cameras[index];
  27117. }
  27118. }
  27119. for (index = this.lights.length - 1; index >= 0; index--) {
  27120. if (this.lights[index].id === id) {
  27121. return this.lights[index];
  27122. }
  27123. }
  27124. return null;
  27125. };
  27126. /**
  27127. * Gets a node (Mesh, Camera, Light) using a given id
  27128. * @param id defines the id to search for
  27129. * @return the found node or null if not found at all
  27130. */
  27131. Scene.prototype.getNodeByID = function (id) {
  27132. var mesh = this.getMeshByID(id);
  27133. if (mesh) {
  27134. return mesh;
  27135. }
  27136. var light = this.getLightByID(id);
  27137. if (light) {
  27138. return light;
  27139. }
  27140. var camera = this.getCameraByID(id);
  27141. if (camera) {
  27142. return camera;
  27143. }
  27144. var bone = this.getBoneByID(id);
  27145. return bone;
  27146. };
  27147. /**
  27148. * Gets a node (Mesh, Camera, Light) using a given name
  27149. * @param name defines the name to search for
  27150. * @return the found node or null if not found at all.
  27151. */
  27152. Scene.prototype.getNodeByName = function (name) {
  27153. var mesh = this.getMeshByName(name);
  27154. if (mesh) {
  27155. return mesh;
  27156. }
  27157. var light = this.getLightByName(name);
  27158. if (light) {
  27159. return light;
  27160. }
  27161. var camera = this.getCameraByName(name);
  27162. if (camera) {
  27163. return camera;
  27164. }
  27165. var bone = this.getBoneByName(name);
  27166. return bone;
  27167. };
  27168. /**
  27169. * Gets a mesh using a given name
  27170. * @param name defines the name to search for
  27171. * @return the found mesh or null if not found at all.
  27172. */
  27173. Scene.prototype.getMeshByName = function (name) {
  27174. for (var index = 0; index < this.meshes.length; index++) {
  27175. if (this.meshes[index].name === name) {
  27176. return this.meshes[index];
  27177. }
  27178. }
  27179. return null;
  27180. };
  27181. /**
  27182. * Gets a transform node using a given name
  27183. * @param name defines the name to search for
  27184. * @return the found transform node or null if not found at all.
  27185. */
  27186. Scene.prototype.getTransformNodeByName = function (name) {
  27187. for (var index = 0; index < this.transformNodes.length; index++) {
  27188. if (this.transformNodes[index].name === name) {
  27189. return this.transformNodes[index];
  27190. }
  27191. }
  27192. return null;
  27193. };
  27194. /**
  27195. * Gets a sound using a given name
  27196. * @param name defines the name to search for
  27197. * @return the found sound or null if not found at all.
  27198. */
  27199. Scene.prototype.getSoundByName = function (name) {
  27200. var index;
  27201. if (BABYLON.AudioEngine) {
  27202. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27203. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27204. return this.mainSoundTrack.soundCollection[index];
  27205. }
  27206. }
  27207. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27208. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27209. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27210. return this.soundTracks[sdIndex].soundCollection[index];
  27211. }
  27212. }
  27213. }
  27214. }
  27215. return null;
  27216. };
  27217. /**
  27218. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27219. * @param id defines the id to search for
  27220. * @return the found skeleton or null if not found at all.
  27221. */
  27222. Scene.prototype.getLastSkeletonByID = function (id) {
  27223. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27224. if (this.skeletons[index].id === id) {
  27225. return this.skeletons[index];
  27226. }
  27227. }
  27228. return null;
  27229. };
  27230. /**
  27231. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27232. * @param id defines the id to search for
  27233. * @return the found skeleton or null if not found at all.
  27234. */
  27235. Scene.prototype.getSkeletonById = function (id) {
  27236. for (var index = 0; index < this.skeletons.length; index++) {
  27237. if (this.skeletons[index].id === id) {
  27238. return this.skeletons[index];
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. /**
  27244. * Gets a skeleton using a given name
  27245. * @param name defines the name to search for
  27246. * @return the found skeleton or null if not found at all.
  27247. */
  27248. Scene.prototype.getSkeletonByName = function (name) {
  27249. for (var index = 0; index < this.skeletons.length; index++) {
  27250. if (this.skeletons[index].name === name) {
  27251. return this.skeletons[index];
  27252. }
  27253. }
  27254. return null;
  27255. };
  27256. /**
  27257. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27258. * @param id defines the id to search for
  27259. * @return the found morph target manager or null if not found at all.
  27260. */
  27261. Scene.prototype.getMorphTargetManagerById = function (id) {
  27262. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27263. if (this.morphTargetManagers[index].uniqueId === id) {
  27264. return this.morphTargetManagers[index];
  27265. }
  27266. }
  27267. return null;
  27268. };
  27269. /**
  27270. * Gets a boolean indicating if the given mesh is active
  27271. * @param mesh defines the mesh to look for
  27272. * @returns true if the mesh is in the active list
  27273. */
  27274. Scene.prototype.isActiveMesh = function (mesh) {
  27275. return (this._activeMeshes.indexOf(mesh) !== -1);
  27276. };
  27277. Object.defineProperty(Scene.prototype, "uid", {
  27278. /**
  27279. * Return a unique id as a string which can serve as an identifier for the scene
  27280. */
  27281. get: function () {
  27282. if (!this._uid) {
  27283. this._uid = BABYLON.Tools.RandomId();
  27284. }
  27285. return this._uid;
  27286. },
  27287. enumerable: true,
  27288. configurable: true
  27289. });
  27290. /**
  27291. * Add an externaly attached data from its key.
  27292. * This method call will fail and return false, if such key already exists.
  27293. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27294. * @param key the unique key that identifies the data
  27295. * @param data the data object to associate to the key for this Engine instance
  27296. * @return true if no such key were already present and the data was added successfully, false otherwise
  27297. */
  27298. Scene.prototype.addExternalData = function (key, data) {
  27299. if (!this._externalData) {
  27300. this._externalData = new BABYLON.StringDictionary();
  27301. }
  27302. return this._externalData.add(key, data);
  27303. };
  27304. /**
  27305. * Get an externaly attached data from its key
  27306. * @param key the unique key that identifies the data
  27307. * @return the associated data, if present (can be null), or undefined if not present
  27308. */
  27309. Scene.prototype.getExternalData = function (key) {
  27310. if (!this._externalData) {
  27311. return null;
  27312. }
  27313. return this._externalData.get(key);
  27314. };
  27315. /**
  27316. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27317. * @param key the unique key that identifies the data
  27318. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27319. * @return the associated data, can be null if the factory returned null.
  27320. */
  27321. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27322. if (!this._externalData) {
  27323. this._externalData = new BABYLON.StringDictionary();
  27324. }
  27325. return this._externalData.getOrAddWithFactory(key, factory);
  27326. };
  27327. /**
  27328. * Remove an externaly attached data from the Engine instance
  27329. * @param key the unique key that identifies the data
  27330. * @return true if the data was successfully removed, false if it doesn't exist
  27331. */
  27332. Scene.prototype.removeExternalData = function (key) {
  27333. return this._externalData.remove(key);
  27334. };
  27335. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27336. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27337. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27338. var step = _a[_i];
  27339. step.action(mesh, subMesh);
  27340. }
  27341. var material = subMesh.getMaterial();
  27342. if (material !== null && material !== undefined) {
  27343. // Render targets
  27344. if (material.getRenderTargetTextures !== undefined) {
  27345. if (this._processedMaterials.indexOf(material) === -1) {
  27346. this._processedMaterials.push(material);
  27347. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27348. }
  27349. }
  27350. // Dispatch
  27351. this._activeIndices.addCount(subMesh.indexCount, false);
  27352. this._renderingManager.dispatch(subMesh, mesh, material);
  27353. }
  27354. }
  27355. };
  27356. /**
  27357. * Clear the processed materials smart array preventing retention point in material dispose.
  27358. */
  27359. Scene.prototype.freeProcessedMaterials = function () {
  27360. this._processedMaterials.dispose();
  27361. };
  27362. /**
  27363. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27364. */
  27365. Scene.prototype.freeActiveMeshes = function () {
  27366. this._activeMeshes.dispose();
  27367. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27368. this.activeCamera._activeMeshes.dispose();
  27369. }
  27370. if (this.activeCameras) {
  27371. for (var i = 0; i < this.activeCameras.length; i++) {
  27372. var activeCamera = this.activeCameras[i];
  27373. if (activeCamera && activeCamera._activeMeshes) {
  27374. activeCamera._activeMeshes.dispose();
  27375. }
  27376. }
  27377. }
  27378. };
  27379. /**
  27380. * Clear the info related to rendering groups preventing retention points during dispose.
  27381. */
  27382. Scene.prototype.freeRenderingGroups = function () {
  27383. if (this._renderingManager) {
  27384. this._renderingManager.freeRenderingGroups();
  27385. }
  27386. if (this.textures) {
  27387. for (var i = 0; i < this.textures.length; i++) {
  27388. var texture = this.textures[i];
  27389. if (texture && texture.renderList) {
  27390. texture.freeRenderingGroups();
  27391. }
  27392. }
  27393. }
  27394. };
  27395. /** @hidden */
  27396. Scene.prototype._isInIntermediateRendering = function () {
  27397. return this._intermediateRendering;
  27398. };
  27399. /**
  27400. * Defines the current active mesh candidate provider
  27401. * @param provider defines the provider to use
  27402. */
  27403. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27404. this._activeMeshCandidateProvider = provider;
  27405. };
  27406. /**
  27407. * Gets the current active mesh candidate provider
  27408. * @returns the current active mesh candidate provider
  27409. */
  27410. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27411. return this._activeMeshCandidateProvider;
  27412. };
  27413. /**
  27414. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27415. * @returns the current scene
  27416. */
  27417. Scene.prototype.freezeActiveMeshes = function () {
  27418. if (!this.activeCamera) {
  27419. return this;
  27420. }
  27421. if (!this._frustumPlanes) {
  27422. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27423. }
  27424. this._evaluateActiveMeshes();
  27425. this._activeMeshesFrozen = true;
  27426. return this;
  27427. };
  27428. /**
  27429. * Use this function to restart evaluating active meshes on every frame
  27430. * @returns the current scene
  27431. */
  27432. Scene.prototype.unfreezeActiveMeshes = function () {
  27433. this._activeMeshesFrozen = false;
  27434. return this;
  27435. };
  27436. Scene.prototype._evaluateActiveMeshes = function () {
  27437. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27438. return;
  27439. }
  27440. if (!this.activeCamera) {
  27441. return;
  27442. }
  27443. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27444. this.activeCamera._activeMeshes.reset();
  27445. this._activeMeshes.reset();
  27446. this._renderingManager.reset();
  27447. this._processedMaterials.reset();
  27448. this._activeParticleSystems.reset();
  27449. this._activeSkeletons.reset();
  27450. this._softwareSkinnedMeshes.reset();
  27451. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27452. var step = _a[_i];
  27453. step.action();
  27454. }
  27455. // Meshes
  27456. var meshes;
  27457. var len;
  27458. var checkIsEnabled = true;
  27459. // Determine mesh candidates
  27460. if (this._activeMeshCandidateProvider !== undefined) {
  27461. // Use _activeMeshCandidateProvider
  27462. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27463. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27464. if (meshes !== undefined) {
  27465. len = meshes.length;
  27466. }
  27467. else {
  27468. len = 0;
  27469. }
  27470. }
  27471. else if (this._selectionOctree !== undefined) {
  27472. // Octree
  27473. var selection = this._selectionOctree.select(this._frustumPlanes);
  27474. meshes = selection.data;
  27475. len = selection.length;
  27476. }
  27477. else {
  27478. // Full scene traversal
  27479. len = this.meshes.length;
  27480. meshes = this.meshes;
  27481. }
  27482. // Check each mesh
  27483. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27484. mesh = meshes[meshIndex];
  27485. if (mesh.isBlocked) {
  27486. continue;
  27487. }
  27488. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27489. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27490. continue;
  27491. }
  27492. mesh.computeWorldMatrix();
  27493. // Intersections
  27494. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27495. this._meshesForIntersections.pushNoDuplicate(mesh);
  27496. }
  27497. // Switch to current LOD
  27498. meshLOD = mesh.getLOD(this.activeCamera);
  27499. if (meshLOD === undefined || meshLOD === null) {
  27500. continue;
  27501. }
  27502. mesh._preActivate();
  27503. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27504. this._activeMeshes.push(mesh);
  27505. this.activeCamera._activeMeshes.push(mesh);
  27506. mesh._activate(this._renderId);
  27507. if (meshLOD !== mesh) {
  27508. meshLOD._activate(this._renderId);
  27509. }
  27510. this._activeMesh(mesh, meshLOD);
  27511. }
  27512. }
  27513. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27514. // Particle systems
  27515. if (this.particlesEnabled) {
  27516. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27517. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27518. var particleSystem = this.particleSystems[particleIndex];
  27519. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27520. continue;
  27521. }
  27522. var emitter = particleSystem.emitter;
  27523. if (!emitter.position || emitter.isEnabled()) {
  27524. this._activeParticleSystems.push(particleSystem);
  27525. particleSystem.animate();
  27526. this._renderingManager.dispatchParticles(particleSystem);
  27527. }
  27528. }
  27529. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27530. }
  27531. };
  27532. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27533. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27534. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27535. mesh.skeleton.prepare();
  27536. }
  27537. if (!mesh.computeBonesUsingShaders) {
  27538. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27539. }
  27540. }
  27541. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27542. var step = _a[_i];
  27543. step.action(sourceMesh, mesh);
  27544. }
  27545. if (mesh !== undefined && mesh !== null
  27546. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27547. // Submeshes Octrees
  27548. var len;
  27549. var subMeshes;
  27550. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27551. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27552. len = intersections.length;
  27553. subMeshes = intersections.data;
  27554. }
  27555. else {
  27556. subMeshes = mesh.subMeshes;
  27557. len = subMeshes.length;
  27558. }
  27559. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27560. subMesh = subMeshes[subIndex];
  27561. this._evaluateSubMesh(subMesh, mesh);
  27562. }
  27563. }
  27564. };
  27565. /**
  27566. * Update the transform matrix to update from the current active camera
  27567. * @param force defines a boolean used to force the update even if cache is up to date
  27568. */
  27569. Scene.prototype.updateTransformMatrix = function (force) {
  27570. if (!this.activeCamera) {
  27571. return;
  27572. }
  27573. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27574. };
  27575. /**
  27576. * 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)
  27577. * @param alternateCamera defines the camera to use
  27578. */
  27579. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27580. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27581. };
  27582. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27583. if (camera && camera._skipRendering) {
  27584. return;
  27585. }
  27586. var engine = this._engine;
  27587. this.activeCamera = camera;
  27588. if (!this.activeCamera)
  27589. throw new Error("Active camera not set");
  27590. // Viewport
  27591. engine.setViewport(this.activeCamera.viewport);
  27592. // Camera
  27593. this.resetCachedMaterial();
  27594. this._renderId++;
  27595. this.updateTransformMatrix();
  27596. if (camera._alternateCamera) {
  27597. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27598. this._alternateRendering = true;
  27599. }
  27600. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27601. // Meshes
  27602. this._evaluateActiveMeshes();
  27603. // Software skinning
  27604. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27605. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27606. mesh.applySkeleton(mesh.skeleton);
  27607. }
  27608. // Render targets
  27609. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27610. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27611. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27612. }
  27613. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27614. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27615. }
  27616. if (this.renderTargetsEnabled) {
  27617. this._intermediateRendering = true;
  27618. if (this._renderTargets.length > 0) {
  27619. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27620. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27621. var renderTarget = this._renderTargets.data[renderIndex];
  27622. if (renderTarget._shouldRender()) {
  27623. this._renderId++;
  27624. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27625. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27626. }
  27627. }
  27628. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27629. this._renderId++;
  27630. }
  27631. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27632. var step = _a[_i];
  27633. step.action(this.activeCamera);
  27634. }
  27635. this._intermediateRendering = false;
  27636. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27637. }
  27638. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27639. // Prepare Frame
  27640. if (this.postProcessManager) {
  27641. this.postProcessManager._prepareFrame();
  27642. }
  27643. // Before Camera Draw
  27644. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27645. var step = _c[_b];
  27646. step.action(this.activeCamera);
  27647. }
  27648. // Render
  27649. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27650. this._renderingManager.render(null, null, true, true);
  27651. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27652. // After Camera Draw
  27653. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27654. var step = _e[_d];
  27655. step.action(this.activeCamera);
  27656. }
  27657. // Finalize frame
  27658. if (this.postProcessManager) {
  27659. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27660. }
  27661. // Reset some special arrays
  27662. this._renderTargets.reset();
  27663. this._alternateRendering = false;
  27664. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27665. };
  27666. Scene.prototype._processSubCameras = function (camera) {
  27667. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27668. this._renderForCamera(camera);
  27669. return;
  27670. }
  27671. // rig cameras
  27672. for (var index = 0; index < camera._rigCameras.length; index++) {
  27673. this._renderForCamera(camera._rigCameras[index], camera);
  27674. }
  27675. this.activeCamera = camera;
  27676. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27677. };
  27678. Scene.prototype._checkIntersections = function () {
  27679. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27680. var sourceMesh = this._meshesForIntersections.data[index];
  27681. if (!sourceMesh.actionManager) {
  27682. continue;
  27683. }
  27684. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27685. var action = sourceMesh.actionManager.actions[actionIndex];
  27686. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27687. var parameters = action.getTriggerParameter();
  27688. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27689. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27690. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27691. if (areIntersecting && currentIntersectionInProgress === -1) {
  27692. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27693. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27694. sourceMesh._intersectionsInProgress.push(otherMesh);
  27695. }
  27696. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27697. sourceMesh._intersectionsInProgress.push(otherMesh);
  27698. }
  27699. }
  27700. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27701. //They intersected, and now they don't.
  27702. //is this trigger an exit trigger? execute an event.
  27703. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27704. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27705. }
  27706. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27707. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27708. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27709. return otherMesh === parameterMesh;
  27710. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27711. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27712. }
  27713. }
  27714. }
  27715. }
  27716. }
  27717. };
  27718. /**
  27719. * Render the scene
  27720. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27721. */
  27722. Scene.prototype.render = function (updateCameras) {
  27723. if (updateCameras === void 0) { updateCameras = true; }
  27724. if (this.isDisposed) {
  27725. return;
  27726. }
  27727. // Register components that have been associated lately to the scene.
  27728. this._registerTransientComponents();
  27729. this._activeParticles.fetchNewFrame();
  27730. this._totalVertices.fetchNewFrame();
  27731. this._activeIndices.fetchNewFrame();
  27732. this._activeBones.fetchNewFrame();
  27733. this._meshesForIntersections.reset();
  27734. this.resetCachedMaterial();
  27735. this.onBeforeAnimationsObservable.notifyObservers(this);
  27736. // Actions
  27737. if (this.actionManager) {
  27738. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27739. }
  27740. if (this._engine.isDeterministicLockStep()) {
  27741. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27742. var defaultFPS = (60.0 / 1000.0);
  27743. var defaultFrameTime = 1000 / 60; // frame time in MS
  27744. if (this._physicsEngine) {
  27745. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27746. }
  27747. var stepsTaken = 0;
  27748. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27749. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27750. internalSteps = Math.min(internalSteps, maxSubSteps);
  27751. do {
  27752. this.onBeforeStepObservable.notifyObservers(this);
  27753. // Animations
  27754. this._animationRatio = defaultFrameTime * defaultFPS;
  27755. this._animate();
  27756. this.onAfterAnimationsObservable.notifyObservers(this);
  27757. // Physics
  27758. if (this._physicsEngine) {
  27759. this.onBeforePhysicsObservable.notifyObservers(this);
  27760. this._physicsEngine._step(defaultFrameTime / 1000);
  27761. this.onAfterPhysicsObservable.notifyObservers(this);
  27762. }
  27763. this.onAfterStepObservable.notifyObservers(this);
  27764. this._currentStepId++;
  27765. stepsTaken++;
  27766. deltaTime -= defaultFrameTime;
  27767. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27768. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27769. }
  27770. else {
  27771. // Animations
  27772. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27773. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27774. this._animate();
  27775. this.onAfterAnimationsObservable.notifyObservers(this);
  27776. // Physics
  27777. if (this._physicsEngine) {
  27778. this.onBeforePhysicsObservable.notifyObservers(this);
  27779. this._physicsEngine._step(deltaTime / 1000.0);
  27780. this.onAfterPhysicsObservable.notifyObservers(this);
  27781. }
  27782. }
  27783. // Before camera update steps
  27784. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27785. var step = _a[_i];
  27786. step.action();
  27787. }
  27788. // Update Cameras
  27789. if (updateCameras) {
  27790. if (this.activeCameras.length > 0) {
  27791. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27792. var camera = this.activeCameras[cameraIndex];
  27793. camera.update();
  27794. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27795. // rig cameras
  27796. for (var index = 0; index < camera._rigCameras.length; index++) {
  27797. camera._rigCameras[index].update();
  27798. }
  27799. }
  27800. }
  27801. }
  27802. else if (this.activeCamera) {
  27803. this.activeCamera.update();
  27804. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27805. // rig cameras
  27806. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27807. this.activeCamera._rigCameras[index].update();
  27808. }
  27809. }
  27810. }
  27811. }
  27812. // Before render
  27813. this.onBeforeRenderObservable.notifyObservers(this);
  27814. // Customs render targets
  27815. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27816. var engine = this.getEngine();
  27817. var currentActiveCamera = this.activeCamera;
  27818. if (this.renderTargetsEnabled) {
  27819. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27820. this._intermediateRendering = true;
  27821. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27822. var renderTarget = this.customRenderTargets[customIndex];
  27823. if (renderTarget._shouldRender()) {
  27824. this._renderId++;
  27825. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27826. if (!this.activeCamera)
  27827. throw new Error("Active camera not set");
  27828. // Viewport
  27829. engine.setViewport(this.activeCamera.viewport);
  27830. // Camera
  27831. this.updateTransformMatrix();
  27832. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27833. }
  27834. }
  27835. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27836. this._intermediateRendering = false;
  27837. this._renderId++;
  27838. }
  27839. // Restore back buffer
  27840. if (this.customRenderTargets.length > 0) {
  27841. engine.restoreDefaultFramebuffer();
  27842. }
  27843. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27844. this.activeCamera = currentActiveCamera;
  27845. // Procedural textures
  27846. if (this.proceduralTexturesEnabled) {
  27847. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27848. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27849. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27850. if (proceduralTexture._shouldRender()) {
  27851. proceduralTexture.render();
  27852. }
  27853. }
  27854. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27855. }
  27856. // Clear
  27857. if (this.autoClearDepthAndStencil || this.autoClear) {
  27858. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27859. }
  27860. // Shadows
  27861. if (this.shadowsEnabled) {
  27862. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27863. var light = this.lights[lightIndex];
  27864. var shadowGenerator = light.getShadowGenerator();
  27865. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27866. var shadowMap = (shadowGenerator.getShadowMap());
  27867. if (this.textures.indexOf(shadowMap) !== -1) {
  27868. this._renderTargets.push(shadowMap);
  27869. }
  27870. }
  27871. }
  27872. }
  27873. // Collects render targets from external components.
  27874. for (var _b = 0, _c = this._gatherRenderTargetsStage; _b < _c.length; _b++) {
  27875. var step = _c[_b];
  27876. step.action(this._renderTargets);
  27877. }
  27878. // Multi-cameras?
  27879. if (this.activeCameras.length > 0) {
  27880. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27881. if (cameraIndex > 0) {
  27882. this._engine.clear(null, false, true, true);
  27883. }
  27884. this._processSubCameras(this.activeCameras[cameraIndex]);
  27885. }
  27886. }
  27887. else {
  27888. if (!this.activeCamera) {
  27889. throw new Error("No camera defined");
  27890. }
  27891. this._processSubCameras(this.activeCamera);
  27892. }
  27893. // Intersection checks
  27894. this._checkIntersections();
  27895. // Update the audio listener attached to the camera
  27896. if (BABYLON.AudioEngine) {
  27897. this._updateAudioParameters();
  27898. }
  27899. // After render
  27900. if (this.afterRender) {
  27901. this.afterRender();
  27902. }
  27903. this.onAfterRenderObservable.notifyObservers(this);
  27904. // Cleaning
  27905. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27906. var data = this._toBeDisposed.data[index];
  27907. if (data) {
  27908. data.dispose();
  27909. }
  27910. this._toBeDisposed[index] = null;
  27911. }
  27912. this._toBeDisposed.reset();
  27913. if (this.dumpNextRenderTargets) {
  27914. this.dumpNextRenderTargets = false;
  27915. }
  27916. this._activeBones.addCount(0, true);
  27917. this._activeIndices.addCount(0, true);
  27918. this._activeParticles.addCount(0, true);
  27919. };
  27920. Scene.prototype._updateAudioParameters = function () {
  27921. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27922. return;
  27923. }
  27924. var listeningCamera;
  27925. var audioEngine = BABYLON.Engine.audioEngine;
  27926. if (this.activeCameras.length > 0) {
  27927. listeningCamera = this.activeCameras[0];
  27928. }
  27929. else {
  27930. listeningCamera = this.activeCamera;
  27931. }
  27932. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27933. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27934. // for VR cameras
  27935. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27936. listeningCamera = listeningCamera.rigCameras[0];
  27937. }
  27938. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27939. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27940. cameraDirection.normalize();
  27941. // To avoid some errors on GearVR
  27942. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27943. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27944. }
  27945. var i;
  27946. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27947. var sound = this.mainSoundTrack.soundCollection[i];
  27948. if (sound.useCustomAttenuation) {
  27949. sound.updateDistanceFromListener();
  27950. }
  27951. }
  27952. for (i = 0; i < this.soundTracks.length; i++) {
  27953. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27954. sound = this.soundTracks[i].soundCollection[j];
  27955. if (sound.useCustomAttenuation) {
  27956. sound.updateDistanceFromListener();
  27957. }
  27958. }
  27959. }
  27960. }
  27961. };
  27962. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27963. // Audio
  27964. /**
  27965. * Gets or sets if audio support is enabled
  27966. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27967. */
  27968. get: function () {
  27969. return this._audioEnabled;
  27970. },
  27971. set: function (value) {
  27972. this._audioEnabled = value;
  27973. if (BABYLON.AudioEngine) {
  27974. if (this._audioEnabled) {
  27975. this._enableAudio();
  27976. }
  27977. else {
  27978. this._disableAudio();
  27979. }
  27980. }
  27981. },
  27982. enumerable: true,
  27983. configurable: true
  27984. });
  27985. Scene.prototype._disableAudio = function () {
  27986. var i;
  27987. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27988. this.mainSoundTrack.soundCollection[i].pause();
  27989. }
  27990. for (i = 0; i < this.soundTracks.length; i++) {
  27991. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27992. this.soundTracks[i].soundCollection[j].pause();
  27993. }
  27994. }
  27995. };
  27996. Scene.prototype._enableAudio = function () {
  27997. var i;
  27998. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27999. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28000. this.mainSoundTrack.soundCollection[i].play();
  28001. }
  28002. }
  28003. for (i = 0; i < this.soundTracks.length; i++) {
  28004. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28005. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28006. this.soundTracks[i].soundCollection[j].play();
  28007. }
  28008. }
  28009. }
  28010. };
  28011. Object.defineProperty(Scene.prototype, "headphone", {
  28012. /**
  28013. * Gets or sets if audio will be output to headphones
  28014. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28015. */
  28016. get: function () {
  28017. return this._headphone;
  28018. },
  28019. set: function (value) {
  28020. this._headphone = value;
  28021. if (BABYLON.AudioEngine) {
  28022. if (this._headphone) {
  28023. this._switchAudioModeForHeadphones();
  28024. }
  28025. else {
  28026. this._switchAudioModeForNormalSpeakers();
  28027. }
  28028. }
  28029. },
  28030. enumerable: true,
  28031. configurable: true
  28032. });
  28033. Scene.prototype._switchAudioModeForHeadphones = function () {
  28034. this.mainSoundTrack.switchPanningModelToHRTF();
  28035. for (var i = 0; i < this.soundTracks.length; i++) {
  28036. this.soundTracks[i].switchPanningModelToHRTF();
  28037. }
  28038. };
  28039. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28040. this.mainSoundTrack.switchPanningModelToEqualPower();
  28041. for (var i = 0; i < this.soundTracks.length; i++) {
  28042. this.soundTracks[i].switchPanningModelToEqualPower();
  28043. }
  28044. };
  28045. /**
  28046. * Freeze all materials
  28047. * A frozen material will not be updatable but should be faster to render
  28048. */
  28049. Scene.prototype.freezeMaterials = function () {
  28050. for (var i = 0; i < this.materials.length; i++) {
  28051. this.materials[i].freeze();
  28052. }
  28053. };
  28054. /**
  28055. * Unfreeze all materials
  28056. * A frozen material will not be updatable but should be faster to render
  28057. */
  28058. Scene.prototype.unfreezeMaterials = function () {
  28059. for (var i = 0; i < this.materials.length; i++) {
  28060. this.materials[i].unfreeze();
  28061. }
  28062. };
  28063. /**
  28064. * Releases all held ressources
  28065. */
  28066. Scene.prototype.dispose = function () {
  28067. this.beforeRender = null;
  28068. this.afterRender = null;
  28069. this.skeletons = [];
  28070. this.morphTargetManagers = [];
  28071. this._transientComponents = [];
  28072. this._isReadyForMeshStage.clear();
  28073. this._beforeEvaluateActiveMeshStage.clear();
  28074. this._evaluateSubMeshStage.clear();
  28075. this._activeMeshStage.clear();
  28076. this._cameraDrawRenderTargetStage.clear();
  28077. this._beforeCameraDrawStage.clear();
  28078. this._beforeRenderingGroupDrawStage.clear();
  28079. this._afterRenderingGroupDrawStage.clear();
  28080. this._afterCameraDrawStage.clear();
  28081. this._beforeCameraUpdateStage.clear();
  28082. this._gatherRenderTargetsStage.clear();
  28083. this._rebuildGeometryStage.clear();
  28084. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28085. var component = _a[_i];
  28086. component.dispose();
  28087. }
  28088. this.importedMeshesFiles = new Array();
  28089. this.stopAllAnimations();
  28090. this.resetCachedMaterial();
  28091. // Smart arrays
  28092. if (this.activeCamera) {
  28093. this.activeCamera._activeMeshes.dispose();
  28094. this.activeCamera = null;
  28095. }
  28096. this._activeMeshes.dispose();
  28097. this._renderingManager.dispose();
  28098. this._processedMaterials.dispose();
  28099. this._activeParticleSystems.dispose();
  28100. this._activeSkeletons.dispose();
  28101. this._softwareSkinnedMeshes.dispose();
  28102. this._renderTargets.dispose();
  28103. this._registeredForLateAnimationBindings.dispose();
  28104. this._meshesForIntersections.dispose();
  28105. this._toBeDisposed.dispose();
  28106. // Abort active requests
  28107. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28108. var request = _c[_b];
  28109. request.abort();
  28110. }
  28111. // Debug layer
  28112. if (this._debugLayer) {
  28113. this._debugLayer.hide();
  28114. }
  28115. // Events
  28116. this.onDisposeObservable.notifyObservers(this);
  28117. this.onDisposeObservable.clear();
  28118. this.onBeforeRenderObservable.clear();
  28119. this.onAfterRenderObservable.clear();
  28120. this.onBeforeRenderTargetsRenderObservable.clear();
  28121. this.onAfterRenderTargetsRenderObservable.clear();
  28122. this.onAfterStepObservable.clear();
  28123. this.onBeforeStepObservable.clear();
  28124. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28125. this.onAfterActiveMeshesEvaluationObservable.clear();
  28126. this.onBeforeParticlesRenderingObservable.clear();
  28127. this.onAfterParticlesRenderingObservable.clear();
  28128. this.onBeforeSpritesRenderingObservable.clear();
  28129. this.onAfterSpritesRenderingObservable.clear();
  28130. this.onBeforeDrawPhaseObservable.clear();
  28131. this.onAfterDrawPhaseObservable.clear();
  28132. this.onBeforePhysicsObservable.clear();
  28133. this.onAfterPhysicsObservable.clear();
  28134. this.onBeforeAnimationsObservable.clear();
  28135. this.onAfterAnimationsObservable.clear();
  28136. this.onDataLoadedObservable.clear();
  28137. this.onBeforeRenderingGroupObservable.clear();
  28138. this.onAfterRenderingGroupObservable.clear();
  28139. this.detachControl();
  28140. // Release sounds & sounds tracks
  28141. if (BABYLON.AudioEngine) {
  28142. this.disposeSounds();
  28143. }
  28144. // VR Helper
  28145. if (this.VRHelper) {
  28146. this.VRHelper.dispose();
  28147. }
  28148. // Detach cameras
  28149. var canvas = this._engine.getRenderingCanvas();
  28150. if (canvas) {
  28151. var index;
  28152. for (index = 0; index < this.cameras.length; index++) {
  28153. this.cameras[index].detachControl(canvas);
  28154. }
  28155. }
  28156. // Release animation groups
  28157. while (this.animationGroups.length) {
  28158. this.animationGroups[0].dispose();
  28159. }
  28160. // Release lights
  28161. while (this.lights.length) {
  28162. this.lights[0].dispose();
  28163. }
  28164. // Release meshes
  28165. while (this.meshes.length) {
  28166. this.meshes[0].dispose(true);
  28167. }
  28168. while (this.transformNodes.length) {
  28169. this.removeTransformNode(this.transformNodes[0]);
  28170. }
  28171. // Release cameras
  28172. while (this.cameras.length) {
  28173. this.cameras[0].dispose();
  28174. }
  28175. // Release materials
  28176. if (this.defaultMaterial) {
  28177. this.defaultMaterial.dispose();
  28178. }
  28179. while (this.multiMaterials.length) {
  28180. this.multiMaterials[0].dispose();
  28181. }
  28182. while (this.materials.length) {
  28183. this.materials[0].dispose();
  28184. }
  28185. // Release particles
  28186. while (this.particleSystems.length) {
  28187. this.particleSystems[0].dispose();
  28188. }
  28189. // Release sprites
  28190. while (this.spriteManagers.length) {
  28191. this.spriteManagers[0].dispose();
  28192. }
  28193. // Release postProcesses
  28194. while (this.postProcesses.length) {
  28195. this.postProcesses[0].dispose();
  28196. }
  28197. // Release textures
  28198. while (this.textures.length) {
  28199. this.textures[0].dispose();
  28200. }
  28201. // Release UBO
  28202. this._sceneUbo.dispose();
  28203. if (this._alternateSceneUbo) {
  28204. this._alternateSceneUbo.dispose();
  28205. }
  28206. // Post-processes
  28207. this.postProcessManager.dispose();
  28208. // Physics
  28209. if (this._physicsEngine) {
  28210. this.disablePhysicsEngine();
  28211. }
  28212. // Remove from engine
  28213. index = this._engine.scenes.indexOf(this);
  28214. if (index > -1) {
  28215. this._engine.scenes.splice(index, 1);
  28216. }
  28217. this._engine.wipeCaches(true);
  28218. this._isDisposed = true;
  28219. };
  28220. Object.defineProperty(Scene.prototype, "isDisposed", {
  28221. /**
  28222. * Gets if the scene is already disposed
  28223. */
  28224. get: function () {
  28225. return this._isDisposed;
  28226. },
  28227. enumerable: true,
  28228. configurable: true
  28229. });
  28230. /**
  28231. * Releases sounds & soundtracks
  28232. */
  28233. Scene.prototype.disposeSounds = function () {
  28234. if (!this._mainSoundTrack) {
  28235. return;
  28236. }
  28237. this.mainSoundTrack.dispose();
  28238. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28239. this.soundTracks[scIndex].dispose();
  28240. }
  28241. };
  28242. /**
  28243. * Call this function to reduce memory footprint of the scene.
  28244. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28245. */
  28246. Scene.prototype.clearCachedVertexData = function () {
  28247. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28248. var mesh = this.meshes[meshIndex];
  28249. var geometry = mesh.geometry;
  28250. if (geometry) {
  28251. geometry._indices = [];
  28252. for (var vbName in geometry._vertexBuffers) {
  28253. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28254. continue;
  28255. }
  28256. geometry._vertexBuffers[vbName]._buffer._data = null;
  28257. }
  28258. }
  28259. }
  28260. };
  28261. /**
  28262. * This function will remove the local cached buffer data from texture.
  28263. * It will save memory but will prevent the texture from being rebuilt
  28264. */
  28265. Scene.prototype.cleanCachedTextureBuffer = function () {
  28266. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28267. var baseTexture = _a[_i];
  28268. var buffer = baseTexture._buffer;
  28269. if (buffer) {
  28270. baseTexture._buffer = null;
  28271. }
  28272. }
  28273. };
  28274. // Octrees
  28275. /**
  28276. * Get the world extend vectors with an optional filter
  28277. *
  28278. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28279. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28280. */
  28281. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28282. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28283. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28284. filterPredicate = filterPredicate || (function () { return true; });
  28285. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28286. mesh.computeWorldMatrix(true);
  28287. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28288. return;
  28289. }
  28290. var boundingInfo = mesh.getBoundingInfo();
  28291. var minBox = boundingInfo.boundingBox.minimumWorld;
  28292. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28293. BABYLON.Tools.CheckExtends(minBox, min, max);
  28294. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28295. });
  28296. return {
  28297. min: min,
  28298. max: max
  28299. };
  28300. };
  28301. /**
  28302. * Creates or updates the octree used to boost selection (picking)
  28303. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28304. * @param maxCapacity defines the maximum capacity per leaf
  28305. * @param maxDepth defines the maximum depth of the octree
  28306. * @returns an octree of AbstractMesh
  28307. */
  28308. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28309. if (maxCapacity === void 0) { maxCapacity = 64; }
  28310. if (maxDepth === void 0) { maxDepth = 2; }
  28311. if (!this._selectionOctree) {
  28312. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28313. }
  28314. var worldExtends = this.getWorldExtends();
  28315. // Update octree
  28316. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28317. return this._selectionOctree;
  28318. };
  28319. // Picking
  28320. /**
  28321. * Creates a ray that can be used to pick in the scene
  28322. * @param x defines the x coordinate of the origin (on-screen)
  28323. * @param y defines the y coordinate of the origin (on-screen)
  28324. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28325. * @param camera defines the camera to use for the picking
  28326. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28327. * @returns a Ray
  28328. */
  28329. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28330. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28331. var result = BABYLON.Ray.Zero();
  28332. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28333. return result;
  28334. };
  28335. /**
  28336. * Creates a ray that can be used to pick in the scene
  28337. * @param x defines the x coordinate of the origin (on-screen)
  28338. * @param y defines the y coordinate of the origin (on-screen)
  28339. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28340. * @param result defines the ray where to store the picking ray
  28341. * @param camera defines the camera to use for the picking
  28342. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28343. * @returns the current scene
  28344. */
  28345. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28346. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28347. var engine = this._engine;
  28348. if (!camera) {
  28349. if (!this.activeCamera)
  28350. throw new Error("Active camera not set");
  28351. camera = this.activeCamera;
  28352. }
  28353. var cameraViewport = camera.viewport;
  28354. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28355. // Moving coordinates to local viewport world
  28356. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28357. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28358. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28359. return this;
  28360. };
  28361. /**
  28362. * Creates a ray that can be used to pick in the scene
  28363. * @param x defines the x coordinate of the origin (on-screen)
  28364. * @param y defines the y coordinate of the origin (on-screen)
  28365. * @param camera defines the camera to use for the picking
  28366. * @returns a Ray
  28367. */
  28368. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28369. var result = BABYLON.Ray.Zero();
  28370. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28371. return result;
  28372. };
  28373. /**
  28374. * Creates a ray that can be used to pick in the scene
  28375. * @param x defines the x coordinate of the origin (on-screen)
  28376. * @param y defines the y coordinate of the origin (on-screen)
  28377. * @param result defines the ray where to store the picking ray
  28378. * @param camera defines the camera to use for the picking
  28379. * @returns the current scene
  28380. */
  28381. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28382. if (!BABYLON.PickingInfo) {
  28383. return this;
  28384. }
  28385. var engine = this._engine;
  28386. if (!camera) {
  28387. if (!this.activeCamera)
  28388. throw new Error("Active camera not set");
  28389. camera = this.activeCamera;
  28390. }
  28391. var cameraViewport = camera.viewport;
  28392. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28393. var identity = BABYLON.Matrix.Identity();
  28394. // Moving coordinates to local viewport world
  28395. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28396. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28397. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28398. return this;
  28399. };
  28400. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28401. if (!BABYLON.PickingInfo) {
  28402. return null;
  28403. }
  28404. var pickingInfo = null;
  28405. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28406. var mesh = this.meshes[meshIndex];
  28407. if (predicate) {
  28408. if (!predicate(mesh)) {
  28409. continue;
  28410. }
  28411. }
  28412. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28413. continue;
  28414. }
  28415. var world = mesh.getWorldMatrix();
  28416. var ray = rayFunction(world);
  28417. var result = mesh.intersects(ray, fastCheck);
  28418. if (!result || !result.hit)
  28419. continue;
  28420. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28421. continue;
  28422. pickingInfo = result;
  28423. if (fastCheck) {
  28424. break;
  28425. }
  28426. }
  28427. return pickingInfo || new BABYLON.PickingInfo();
  28428. };
  28429. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28430. if (!BABYLON.PickingInfo) {
  28431. return null;
  28432. }
  28433. var pickingInfos = new Array();
  28434. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28435. var mesh = this.meshes[meshIndex];
  28436. if (predicate) {
  28437. if (!predicate(mesh)) {
  28438. continue;
  28439. }
  28440. }
  28441. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28442. continue;
  28443. }
  28444. var world = mesh.getWorldMatrix();
  28445. var ray = rayFunction(world);
  28446. var result = mesh.intersects(ray, false);
  28447. if (!result || !result.hit)
  28448. continue;
  28449. pickingInfos.push(result);
  28450. }
  28451. return pickingInfos;
  28452. };
  28453. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28454. if (!BABYLON.PickingInfo) {
  28455. return null;
  28456. }
  28457. var pickingInfo = null;
  28458. if (!camera) {
  28459. if (!this.activeCamera) {
  28460. return null;
  28461. }
  28462. camera = this.activeCamera;
  28463. }
  28464. if (this.spriteManagers.length > 0) {
  28465. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28466. var spriteManager = this.spriteManagers[spriteIndex];
  28467. if (!spriteManager.isPickable) {
  28468. continue;
  28469. }
  28470. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28471. if (!result || !result.hit)
  28472. continue;
  28473. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28474. continue;
  28475. pickingInfo = result;
  28476. if (fastCheck) {
  28477. break;
  28478. }
  28479. }
  28480. }
  28481. return pickingInfo || new BABYLON.PickingInfo();
  28482. };
  28483. /** Launch a ray to try to pick a mesh in the scene
  28484. * @param x position on screen
  28485. * @param y position on screen
  28486. * @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
  28487. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28488. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28489. * @returns a PickingInfo
  28490. */
  28491. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28492. var _this = this;
  28493. if (!BABYLON.PickingInfo) {
  28494. return null;
  28495. }
  28496. var result = this._internalPick(function (world) {
  28497. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28498. return _this._tempPickingRay;
  28499. }, predicate, fastCheck);
  28500. if (result) {
  28501. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28502. }
  28503. return result;
  28504. };
  28505. /** Launch a ray to try to pick a sprite in the scene
  28506. * @param x position on screen
  28507. * @param y position on screen
  28508. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28509. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28510. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28511. * @returns a PickingInfo
  28512. */
  28513. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28514. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28515. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28516. };
  28517. /** Use the given ray to pick a mesh in the scene
  28518. * @param ray The ray to use to pick meshes
  28519. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28520. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28521. * @returns a PickingInfo
  28522. */
  28523. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28524. var _this = this;
  28525. var result = this._internalPick(function (world) {
  28526. if (!_this._pickWithRayInverseMatrix) {
  28527. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28528. }
  28529. world.invertToRef(_this._pickWithRayInverseMatrix);
  28530. if (!_this._cachedRayForTransform) {
  28531. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28532. }
  28533. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28534. return _this._cachedRayForTransform;
  28535. }, predicate, fastCheck);
  28536. if (result) {
  28537. result.ray = ray;
  28538. }
  28539. return result;
  28540. };
  28541. /**
  28542. * Launch a ray to try to pick a mesh in the scene
  28543. * @param x X position on screen
  28544. * @param y Y position on screen
  28545. * @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
  28546. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28547. * @returns an array of PickingInfo
  28548. */
  28549. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28550. var _this = this;
  28551. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28552. };
  28553. /**
  28554. * Launch a ray to try to pick a mesh in the scene
  28555. * @param ray Ray to use
  28556. * @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
  28557. * @returns an array of PickingInfo
  28558. */
  28559. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28560. var _this = this;
  28561. return this._internalMultiPick(function (world) {
  28562. if (!_this._pickWithRayInverseMatrix) {
  28563. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28564. }
  28565. world.invertToRef(_this._pickWithRayInverseMatrix);
  28566. if (!_this._cachedRayForTransform) {
  28567. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28568. }
  28569. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28570. return _this._cachedRayForTransform;
  28571. }, predicate);
  28572. };
  28573. /**
  28574. * Force the value of meshUnderPointer
  28575. * @param mesh defines the mesh to use
  28576. */
  28577. Scene.prototype.setPointerOverMesh = function (mesh) {
  28578. if (this._pointerOverMesh === mesh) {
  28579. return;
  28580. }
  28581. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28582. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28583. }
  28584. this._pointerOverMesh = mesh;
  28585. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28586. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28587. }
  28588. };
  28589. /**
  28590. * Gets the mesh under the pointer
  28591. * @returns a Mesh or null if no mesh is under the pointer
  28592. */
  28593. Scene.prototype.getPointerOverMesh = function () {
  28594. return this._pointerOverMesh;
  28595. };
  28596. /**
  28597. * Force the sprite under the pointer
  28598. * @param sprite defines the sprite to use
  28599. */
  28600. Scene.prototype.setPointerOverSprite = function (sprite) {
  28601. if (this._pointerOverSprite === sprite) {
  28602. return;
  28603. }
  28604. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28605. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28606. }
  28607. this._pointerOverSprite = sprite;
  28608. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28609. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28610. }
  28611. };
  28612. /**
  28613. * Gets the sprite under the pointer
  28614. * @returns a Sprite or null if no sprite is under the pointer
  28615. */
  28616. Scene.prototype.getPointerOverSprite = function () {
  28617. return this._pointerOverSprite;
  28618. };
  28619. // Physics
  28620. /**
  28621. * Gets the current physics engine
  28622. * @returns a PhysicsEngine or null if none attached
  28623. */
  28624. Scene.prototype.getPhysicsEngine = function () {
  28625. return this._physicsEngine;
  28626. };
  28627. /**
  28628. * Enables physics to the current scene
  28629. * @param gravity defines the scene's gravity for the physics engine
  28630. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28631. * @return a boolean indicating if the physics engine was initialized
  28632. */
  28633. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28634. if (gravity === void 0) { gravity = null; }
  28635. if (this._physicsEngine) {
  28636. return true;
  28637. }
  28638. try {
  28639. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28640. return true;
  28641. }
  28642. catch (e) {
  28643. BABYLON.Tools.Error(e.message);
  28644. return false;
  28645. }
  28646. };
  28647. /**
  28648. * Disables and disposes the physics engine associated with the scene
  28649. */
  28650. Scene.prototype.disablePhysicsEngine = function () {
  28651. if (!this._physicsEngine) {
  28652. return;
  28653. }
  28654. this._physicsEngine.dispose();
  28655. this._physicsEngine = null;
  28656. };
  28657. /**
  28658. * Gets a boolean indicating if there is an active physics engine
  28659. * @returns a boolean indicating if there is an active physics engine
  28660. */
  28661. Scene.prototype.isPhysicsEnabled = function () {
  28662. return this._physicsEngine !== undefined;
  28663. };
  28664. /**
  28665. * Deletes a physics compound impostor
  28666. * @param compound defines the compound to delete
  28667. */
  28668. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28669. var mesh = compound.parts[0].mesh;
  28670. if (mesh.physicsImpostor) {
  28671. mesh.physicsImpostor.dispose( /*true*/);
  28672. mesh.physicsImpostor = null;
  28673. }
  28674. };
  28675. // Misc.
  28676. /** @hidden */
  28677. Scene.prototype._rebuildGeometries = function () {
  28678. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28679. var geometry = _a[_i];
  28680. geometry._rebuild();
  28681. }
  28682. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28683. var mesh = _c[_b];
  28684. mesh._rebuild();
  28685. }
  28686. if (this.postProcessManager) {
  28687. this.postProcessManager._rebuild();
  28688. }
  28689. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28690. var component = _e[_d];
  28691. component.rebuild();
  28692. }
  28693. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28694. var system = _g[_f];
  28695. system.rebuild();
  28696. }
  28697. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28698. var step = _j[_h];
  28699. step.action();
  28700. }
  28701. };
  28702. /** @hidden */
  28703. Scene.prototype._rebuildTextures = function () {
  28704. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28705. var texture = _a[_i];
  28706. texture._rebuild();
  28707. }
  28708. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28709. };
  28710. /**
  28711. * Creates a default light for the scene.
  28712. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28713. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28714. */
  28715. Scene.prototype.createDefaultLight = function (replace) {
  28716. if (replace === void 0) { replace = false; }
  28717. // Dispose existing light in replace mode.
  28718. if (replace) {
  28719. if (this.lights) {
  28720. for (var i = 0; i < this.lights.length; i++) {
  28721. this.lights[i].dispose();
  28722. }
  28723. }
  28724. }
  28725. // Light
  28726. if (this.lights.length === 0) {
  28727. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28728. }
  28729. };
  28730. /**
  28731. * Creates a default camera for the scene.
  28732. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28733. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28734. * @param replace has default false, when true replaces the active camera in the scene
  28735. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28736. */
  28737. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28738. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28739. if (replace === void 0) { replace = false; }
  28740. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28741. // Dispose existing camera in replace mode.
  28742. if (replace) {
  28743. if (this.activeCamera) {
  28744. this.activeCamera.dispose();
  28745. this.activeCamera = null;
  28746. }
  28747. }
  28748. // Camera
  28749. if (!this.activeCamera) {
  28750. var worldExtends = this.getWorldExtends();
  28751. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28752. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28753. var camera;
  28754. var radius = worldSize.length() * 1.5;
  28755. // empty scene scenario!
  28756. if (!isFinite(radius)) {
  28757. radius = 1;
  28758. worldCenter.copyFromFloats(0, 0, 0);
  28759. }
  28760. if (createArcRotateCamera) {
  28761. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28762. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28763. arcRotateCamera.wheelPrecision = 100 / radius;
  28764. camera = arcRotateCamera;
  28765. }
  28766. else {
  28767. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28768. freeCamera.setTarget(worldCenter);
  28769. camera = freeCamera;
  28770. }
  28771. camera.minZ = radius * 0.01;
  28772. camera.maxZ = radius * 1000;
  28773. camera.speed = radius * 0.2;
  28774. this.activeCamera = camera;
  28775. var canvas = this.getEngine().getRenderingCanvas();
  28776. if (attachCameraControls && canvas) {
  28777. camera.attachControl(canvas);
  28778. }
  28779. }
  28780. };
  28781. /**
  28782. * Creates a default camera and a default light.
  28783. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28784. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28785. * @param replace has the default false, when true replaces the active camera/light in the scene
  28786. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28787. */
  28788. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28789. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28790. if (replace === void 0) { replace = false; }
  28791. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28792. this.createDefaultLight(replace);
  28793. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28794. };
  28795. /**
  28796. * Creates a new sky box
  28797. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28798. * @param environmentTexture defines the texture to use as environment texture
  28799. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28800. * @param scale defines the overall scale of the skybox
  28801. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28802. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28803. * @returns a new mesh holding the sky box
  28804. */
  28805. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28806. if (pbr === void 0) { pbr = false; }
  28807. if (scale === void 0) { scale = 1000; }
  28808. if (blur === void 0) { blur = 0; }
  28809. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28810. if (!environmentTexture) {
  28811. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28812. return null;
  28813. }
  28814. if (setGlobalEnvTexture) {
  28815. if (environmentTexture) {
  28816. this.environmentTexture = environmentTexture;
  28817. }
  28818. }
  28819. // Skybox
  28820. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28821. if (pbr) {
  28822. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28823. hdrSkyboxMaterial.backFaceCulling = false;
  28824. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28825. if (hdrSkyboxMaterial.reflectionTexture) {
  28826. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28827. }
  28828. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28829. hdrSkyboxMaterial.disableLighting = true;
  28830. hdrSkyboxMaterial.twoSidedLighting = true;
  28831. hdrSkybox.infiniteDistance = true;
  28832. hdrSkybox.material = hdrSkyboxMaterial;
  28833. }
  28834. else {
  28835. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28836. skyboxMaterial.backFaceCulling = false;
  28837. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28838. if (skyboxMaterial.reflectionTexture) {
  28839. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28840. }
  28841. skyboxMaterial.disableLighting = true;
  28842. hdrSkybox.infiniteDistance = true;
  28843. hdrSkybox.material = skyboxMaterial;
  28844. }
  28845. return hdrSkybox;
  28846. };
  28847. /**
  28848. * Creates a new environment
  28849. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28850. * @param options defines the options you can use to configure the environment
  28851. * @returns the new EnvironmentHelper
  28852. */
  28853. Scene.prototype.createDefaultEnvironment = function (options) {
  28854. if (BABYLON.EnvironmentHelper) {
  28855. return new BABYLON.EnvironmentHelper(options, this);
  28856. }
  28857. return null;
  28858. };
  28859. /**
  28860. * Creates a new VREXperienceHelper
  28861. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28862. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28863. * @returns a new VREXperienceHelper
  28864. */
  28865. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28866. if (webVROptions === void 0) { webVROptions = {}; }
  28867. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28868. };
  28869. // Tags
  28870. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28871. if (tagsQuery === undefined) {
  28872. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28873. return list;
  28874. }
  28875. var listByTags = [];
  28876. forEach = forEach || (function (item) { return; });
  28877. for (var i in list) {
  28878. var item = list[i];
  28879. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28880. listByTags.push(item);
  28881. forEach(item);
  28882. }
  28883. }
  28884. return listByTags;
  28885. };
  28886. /**
  28887. * Get a list of meshes by tags
  28888. * @param tagsQuery defines the tags query to use
  28889. * @param forEach defines a predicate used to filter results
  28890. * @returns an array of Mesh
  28891. */
  28892. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28893. return this._getByTags(this.meshes, tagsQuery, forEach);
  28894. };
  28895. /**
  28896. * Get a list of cameras by tags
  28897. * @param tagsQuery defines the tags query to use
  28898. * @param forEach defines a predicate used to filter results
  28899. * @returns an array of Camera
  28900. */
  28901. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28902. return this._getByTags(this.cameras, tagsQuery, forEach);
  28903. };
  28904. /**
  28905. * Get a list of lights by tags
  28906. * @param tagsQuery defines the tags query to use
  28907. * @param forEach defines a predicate used to filter results
  28908. * @returns an array of Light
  28909. */
  28910. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28911. return this._getByTags(this.lights, tagsQuery, forEach);
  28912. };
  28913. /**
  28914. * Get a list of materials by tags
  28915. * @param tagsQuery defines the tags query to use
  28916. * @param forEach defines a predicate used to filter results
  28917. * @returns an array of Material
  28918. */
  28919. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28920. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28921. };
  28922. /**
  28923. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28924. * This allowed control for front to back rendering or reversly depending of the special needs.
  28925. *
  28926. * @param renderingGroupId The rendering group id corresponding to its index
  28927. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28928. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28929. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28930. */
  28931. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28932. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28933. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28934. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28935. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28936. };
  28937. /**
  28938. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28939. *
  28940. * @param renderingGroupId The rendering group id corresponding to its index
  28941. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28942. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28943. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28944. */
  28945. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28946. if (depth === void 0) { depth = true; }
  28947. if (stencil === void 0) { stencil = true; }
  28948. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28949. };
  28950. /**
  28951. * Gets the current auto clear configuration for one rendering group of the rendering
  28952. * manager.
  28953. * @param index the rendering group index to get the information for
  28954. * @returns The auto clear setup for the requested rendering group
  28955. */
  28956. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28957. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28958. };
  28959. /**
  28960. * Will flag all materials as dirty to trigger new shader compilation
  28961. * @param flag defines the flag used to specify which material part must be marked as dirty
  28962. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28963. */
  28964. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28965. if (this.blockMaterialDirtyMechanism) {
  28966. return;
  28967. }
  28968. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28969. var material = _a[_i];
  28970. if (predicate && !predicate(material)) {
  28971. continue;
  28972. }
  28973. material.markAsDirty(flag);
  28974. }
  28975. };
  28976. /** @hidden */
  28977. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28978. var _this = this;
  28979. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28980. this._activeRequests.push(request);
  28981. request.onCompleteObservable.add(function (request) {
  28982. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28983. });
  28984. return request;
  28985. };
  28986. /** @hidden */
  28987. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28988. var _this = this;
  28989. return new Promise(function (resolve, reject) {
  28990. _this._loadFile(url, function (data) {
  28991. resolve(data);
  28992. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28993. reject(exception);
  28994. });
  28995. });
  28996. };
  28997. // Statics
  28998. Scene._uniqueIdCounter = 0;
  28999. /** The fog is deactivated */
  29000. Scene.FOGMODE_NONE = 0;
  29001. /** The fog density is following an exponential function */
  29002. Scene.FOGMODE_EXP = 1;
  29003. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29004. Scene.FOGMODE_EXP2 = 2;
  29005. /** The fog density is following a linear function. */
  29006. Scene.FOGMODE_LINEAR = 3;
  29007. /**
  29008. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29009. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29010. */
  29011. Scene.MinDeltaTime = 1.0;
  29012. /**
  29013. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29014. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29015. */
  29016. Scene.MaxDeltaTime = 1000.0;
  29017. /** The distance in pixel that you have to move to prevent some events */
  29018. Scene.DragMovementThreshold = 10; // in pixels
  29019. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29020. Scene.LongPressDelay = 500; // in milliseconds
  29021. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29022. Scene.DoubleClickDelay = 300; // in milliseconds
  29023. /** If you need to check double click without raising a single click at first click, enable this flag */
  29024. Scene.ExclusiveDoubleClickMode = false;
  29025. return Scene;
  29026. }(BABYLON.AbstractScene));
  29027. BABYLON.Scene = Scene;
  29028. })(BABYLON || (BABYLON = {}));
  29029. //# sourceMappingURL=babylon.scene.js.map
  29030. var BABYLON;
  29031. (function (BABYLON) {
  29032. /**
  29033. * Set of assets to keep when moving a scene into an asset container.
  29034. */
  29035. var KeepAssets = /** @class */ (function (_super) {
  29036. __extends(KeepAssets, _super);
  29037. function KeepAssets() {
  29038. return _super !== null && _super.apply(this, arguments) || this;
  29039. }
  29040. return KeepAssets;
  29041. }(BABYLON.AbstractScene));
  29042. BABYLON.KeepAssets = KeepAssets;
  29043. /**
  29044. * Container with a set of assets that can be added or removed from a scene.
  29045. */
  29046. var AssetContainer = /** @class */ (function (_super) {
  29047. __extends(AssetContainer, _super);
  29048. /**
  29049. * Instantiates an AssetContainer.
  29050. * @param scene The scene the AssetContainer belongs to.
  29051. */
  29052. function AssetContainer(scene) {
  29053. var _this = _super.call(this) || this;
  29054. _this.scene = scene;
  29055. return _this;
  29056. }
  29057. /**
  29058. * Adds all the assets from the container to the scene.
  29059. */
  29060. AssetContainer.prototype.addAllToScene = function () {
  29061. var _this = this;
  29062. this.cameras.forEach(function (o) {
  29063. _this.scene.addCamera(o);
  29064. });
  29065. this.lights.forEach(function (o) {
  29066. _this.scene.addLight(o);
  29067. });
  29068. this.meshes.forEach(function (o) {
  29069. _this.scene.addMesh(o);
  29070. });
  29071. this.skeletons.forEach(function (o) {
  29072. _this.scene.addSkeleton(o);
  29073. });
  29074. this.animations.forEach(function (o) {
  29075. _this.scene.addAnimation(o);
  29076. });
  29077. this.animationGroups.forEach(function (o) {
  29078. _this.scene.addAnimationGroup(o);
  29079. });
  29080. this.multiMaterials.forEach(function (o) {
  29081. _this.scene.addMultiMaterial(o);
  29082. });
  29083. this.materials.forEach(function (o) {
  29084. _this.scene.addMaterial(o);
  29085. });
  29086. this.morphTargetManagers.forEach(function (o) {
  29087. _this.scene.addMorphTargetManager(o);
  29088. });
  29089. this.geometries.forEach(function (o) {
  29090. _this.scene.addGeometry(o);
  29091. });
  29092. this.transformNodes.forEach(function (o) {
  29093. _this.scene.addTransformNode(o);
  29094. });
  29095. this.actionManagers.forEach(function (o) {
  29096. _this.scene.addActionManager(o);
  29097. });
  29098. this.sounds.forEach(function (o) {
  29099. o.play();
  29100. o.autoplay = true;
  29101. _this.scene.mainSoundTrack.AddSound(o);
  29102. });
  29103. this.textures.forEach(function (o) {
  29104. _this.scene.addTexture(o);
  29105. });
  29106. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29107. var component = _a[_i];
  29108. component.addFromContainer(this.scene);
  29109. }
  29110. };
  29111. /**
  29112. * Removes all the assets in the container from the scene
  29113. */
  29114. AssetContainer.prototype.removeAllFromScene = function () {
  29115. var _this = this;
  29116. this.cameras.forEach(function (o) {
  29117. _this.scene.removeCamera(o);
  29118. });
  29119. this.lights.forEach(function (o) {
  29120. _this.scene.removeLight(o);
  29121. });
  29122. this.meshes.forEach(function (o) {
  29123. _this.scene.removeMesh(o);
  29124. });
  29125. this.skeletons.forEach(function (o) {
  29126. _this.scene.removeSkeleton(o);
  29127. });
  29128. this.animations.forEach(function (o) {
  29129. _this.scene.removeAnimation(o);
  29130. });
  29131. this.animationGroups.forEach(function (o) {
  29132. _this.scene.removeAnimationGroup(o);
  29133. });
  29134. this.multiMaterials.forEach(function (o) {
  29135. _this.scene.removeMultiMaterial(o);
  29136. });
  29137. this.materials.forEach(function (o) {
  29138. _this.scene.removeMaterial(o);
  29139. });
  29140. this.morphTargetManagers.forEach(function (o) {
  29141. _this.scene.removeMorphTargetManager(o);
  29142. });
  29143. this.geometries.forEach(function (o) {
  29144. _this.scene.removeGeometry(o);
  29145. });
  29146. this.transformNodes.forEach(function (o) {
  29147. _this.scene.removeTransformNode(o);
  29148. });
  29149. this.actionManagers.forEach(function (o) {
  29150. _this.scene.removeActionManager(o);
  29151. });
  29152. this.sounds.forEach(function (o) {
  29153. o.stop();
  29154. o.autoplay = false;
  29155. _this.scene.mainSoundTrack.RemoveSound(o);
  29156. });
  29157. this.textures.forEach(function (o) {
  29158. _this.scene.removeTexture(o);
  29159. });
  29160. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29161. var component = _a[_i];
  29162. component.removeFromContainer(this.scene);
  29163. }
  29164. };
  29165. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29166. if (!sourceAssets) {
  29167. return;
  29168. }
  29169. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29170. var asset = sourceAssets_1[_i];
  29171. var move = true;
  29172. if (keepAssets) {
  29173. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29174. var keepAsset = keepAssets_1[_a];
  29175. if (asset === keepAsset) {
  29176. move = false;
  29177. break;
  29178. }
  29179. }
  29180. }
  29181. if (move) {
  29182. targetAssets.push(asset);
  29183. }
  29184. }
  29185. };
  29186. /**
  29187. * Removes all the assets contained in the scene and adds them to the container.
  29188. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29189. */
  29190. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29191. if (keepAssets === undefined) {
  29192. keepAssets = new KeepAssets();
  29193. }
  29194. for (var key in this) {
  29195. if (this.hasOwnProperty(key)) {
  29196. this[key] = this[key] || [];
  29197. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29198. }
  29199. }
  29200. this.removeAllFromScene();
  29201. };
  29202. /**
  29203. * 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.
  29204. * @returns the root mesh
  29205. */
  29206. AssetContainer.prototype.createRootMesh = function () {
  29207. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29208. this.meshes.forEach(function (m) {
  29209. if (!m.parent) {
  29210. rootMesh.addChild(m);
  29211. }
  29212. });
  29213. this.meshes.unshift(rootMesh);
  29214. return rootMesh;
  29215. };
  29216. return AssetContainer;
  29217. }(BABYLON.AbstractScene));
  29218. BABYLON.AssetContainer = AssetContainer;
  29219. })(BABYLON || (BABYLON = {}));
  29220. //# sourceMappingURL=babylon.assetContainer.js.map
  29221. var BABYLON;
  29222. (function (BABYLON) {
  29223. var Buffer = /** @class */ (function () {
  29224. /**
  29225. * Constructor
  29226. * @param engine the engine
  29227. * @param data the data to use for this buffer
  29228. * @param updatable whether the data is updatable
  29229. * @param stride the stride (optional)
  29230. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29231. * @param instanced whether the buffer is instanced (optional)
  29232. * @param useBytes set to true if the stride in in bytes (optional)
  29233. */
  29234. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29235. if (stride === void 0) { stride = 0; }
  29236. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29237. if (instanced === void 0) { instanced = false; }
  29238. if (useBytes === void 0) { useBytes = false; }
  29239. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29240. this._engine = engine.getScene().getEngine();
  29241. }
  29242. else {
  29243. this._engine = engine;
  29244. }
  29245. this._updatable = updatable;
  29246. this._instanced = instanced;
  29247. this._data = data;
  29248. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29249. if (!postponeInternalCreation) { // by default
  29250. this.create();
  29251. }
  29252. }
  29253. /**
  29254. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29255. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29256. * @param offset defines offset in the buffer (0 by default)
  29257. * @param size defines the size in floats of attributes (position is 3 for instance)
  29258. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29259. * @param instanced defines if the vertex buffer contains indexed data
  29260. * @param useBytes defines if the offset and stride are in bytes
  29261. * @returns the new vertex buffer
  29262. */
  29263. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29264. if (useBytes === void 0) { useBytes = false; }
  29265. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29266. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29267. // a lot of these parameters are ignored as they are overriden by the buffer
  29268. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29269. };
  29270. // Properties
  29271. Buffer.prototype.isUpdatable = function () {
  29272. return this._updatable;
  29273. };
  29274. Buffer.prototype.getData = function () {
  29275. return this._data;
  29276. };
  29277. Buffer.prototype.getBuffer = function () {
  29278. return this._buffer;
  29279. };
  29280. /**
  29281. * Gets the stride in float32 units (i.e. byte stride / 4).
  29282. * May not be an integer if the byte stride is not divisible by 4.
  29283. * DEPRECATED. Use byteStride instead.
  29284. * @returns the stride in float32 units
  29285. */
  29286. Buffer.prototype.getStrideSize = function () {
  29287. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29288. };
  29289. // Methods
  29290. Buffer.prototype.create = function (data) {
  29291. if (data === void 0) { data = null; }
  29292. if (!data && this._buffer) {
  29293. return; // nothing to do
  29294. }
  29295. data = data || this._data;
  29296. if (!data) {
  29297. return;
  29298. }
  29299. if (!this._buffer) { // create buffer
  29300. if (this._updatable) {
  29301. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29302. this._data = data;
  29303. }
  29304. else {
  29305. this._buffer = this._engine.createVertexBuffer(data);
  29306. }
  29307. }
  29308. else if (this._updatable) { // update buffer
  29309. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29310. this._data = data;
  29311. }
  29312. };
  29313. /** @hidden */
  29314. Buffer.prototype._rebuild = function () {
  29315. this._buffer = null;
  29316. this.create(this._data);
  29317. };
  29318. Buffer.prototype.update = function (data) {
  29319. this.create(data);
  29320. };
  29321. /**
  29322. * Updates the data directly.
  29323. * @param data the new data
  29324. * @param offset the new offset
  29325. * @param vertexCount the vertex count (optional)
  29326. * @param useBytes set to true if the offset is in bytes
  29327. */
  29328. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29329. if (useBytes === void 0) { useBytes = false; }
  29330. if (!this._buffer) {
  29331. return;
  29332. }
  29333. if (this._updatable) { // update buffer
  29334. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29335. this._data = null;
  29336. }
  29337. };
  29338. Buffer.prototype.dispose = function () {
  29339. if (!this._buffer) {
  29340. return;
  29341. }
  29342. if (this._engine._releaseBuffer(this._buffer)) {
  29343. this._buffer = null;
  29344. }
  29345. };
  29346. return Buffer;
  29347. }());
  29348. BABYLON.Buffer = Buffer;
  29349. })(BABYLON || (BABYLON = {}));
  29350. //# sourceMappingURL=babylon.buffer.js.map
  29351. var BABYLON;
  29352. (function (BABYLON) {
  29353. var VertexBuffer = /** @class */ (function () {
  29354. /**
  29355. * Constructor
  29356. * @param engine the engine
  29357. * @param data the data to use for this vertex buffer
  29358. * @param kind the vertex buffer kind
  29359. * @param updatable whether the data is updatable
  29360. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29361. * @param stride the stride (optional)
  29362. * @param instanced whether the buffer is instanced (optional)
  29363. * @param offset the offset of the data (optional)
  29364. * @param size the number of components (optional)
  29365. * @param type the type of the component (optional)
  29366. * @param normalized whether the data contains normalized data (optional)
  29367. * @param useBytes set to true if stride and offset are in bytes (optional)
  29368. */
  29369. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29370. if (normalized === void 0) { normalized = false; }
  29371. if (useBytes === void 0) { useBytes = false; }
  29372. if (data instanceof BABYLON.Buffer) {
  29373. this._buffer = data;
  29374. this._ownsBuffer = false;
  29375. }
  29376. else {
  29377. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29378. this._ownsBuffer = true;
  29379. }
  29380. this._kind = kind;
  29381. if (type == undefined) {
  29382. var data_1 = this.getData();
  29383. this.type = VertexBuffer.FLOAT;
  29384. if (data_1 instanceof Int8Array)
  29385. this.type = VertexBuffer.BYTE;
  29386. else if (data_1 instanceof Uint8Array)
  29387. this.type = VertexBuffer.UNSIGNED_BYTE;
  29388. else if (data_1 instanceof Int16Array)
  29389. this.type = VertexBuffer.SHORT;
  29390. else if (data_1 instanceof Uint16Array)
  29391. this.type = VertexBuffer.UNSIGNED_SHORT;
  29392. else if (data_1 instanceof Int32Array)
  29393. this.type = VertexBuffer.INT;
  29394. else if (data_1 instanceof Uint32Array)
  29395. this.type = VertexBuffer.UNSIGNED_INT;
  29396. }
  29397. else {
  29398. this.type = type;
  29399. }
  29400. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29401. if (useBytes) {
  29402. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29403. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29404. this.byteOffset = offset || 0;
  29405. }
  29406. else {
  29407. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29408. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29409. this.byteOffset = (offset || 0) * typeByteLength;
  29410. }
  29411. this.normalized = normalized;
  29412. this._instanced = instanced !== undefined ? instanced : false;
  29413. this._instanceDivisor = instanced ? 1 : 0;
  29414. }
  29415. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29416. /**
  29417. * Gets or sets the instance divisor when in instanced mode
  29418. */
  29419. get: function () {
  29420. return this._instanceDivisor;
  29421. },
  29422. set: function (value) {
  29423. this._instanceDivisor = value;
  29424. if (value == 0) {
  29425. this._instanced = false;
  29426. }
  29427. else {
  29428. this._instanced = true;
  29429. }
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. /** @hidden */
  29435. VertexBuffer.prototype._rebuild = function () {
  29436. if (!this._buffer) {
  29437. return;
  29438. }
  29439. this._buffer._rebuild();
  29440. };
  29441. /**
  29442. * Returns the kind of the VertexBuffer (string).
  29443. */
  29444. VertexBuffer.prototype.getKind = function () {
  29445. return this._kind;
  29446. };
  29447. // Properties
  29448. /**
  29449. * Boolean : is the VertexBuffer updatable ?
  29450. */
  29451. VertexBuffer.prototype.isUpdatable = function () {
  29452. return this._buffer.isUpdatable();
  29453. };
  29454. /**
  29455. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29456. */
  29457. VertexBuffer.prototype.getData = function () {
  29458. return this._buffer.getData();
  29459. };
  29460. /**
  29461. * Returns the WebGLBuffer associated to the VertexBuffer.
  29462. */
  29463. VertexBuffer.prototype.getBuffer = function () {
  29464. return this._buffer.getBuffer();
  29465. };
  29466. /**
  29467. * Returns the stride as a multiple of the type byte length.
  29468. * DEPRECATED. Use byteStride instead.
  29469. */
  29470. VertexBuffer.prototype.getStrideSize = function () {
  29471. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29472. };
  29473. /**
  29474. * Returns the offset as a multiple of the type byte length.
  29475. * DEPRECATED. Use byteOffset instead.
  29476. */
  29477. VertexBuffer.prototype.getOffset = function () {
  29478. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29479. };
  29480. /**
  29481. * Returns the number of components per vertex attribute (integer).
  29482. */
  29483. VertexBuffer.prototype.getSize = function () {
  29484. return this._size;
  29485. };
  29486. /**
  29487. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29488. */
  29489. VertexBuffer.prototype.getIsInstanced = function () {
  29490. return this._instanced;
  29491. };
  29492. /**
  29493. * Returns the instancing divisor, zero for non-instanced (integer).
  29494. */
  29495. VertexBuffer.prototype.getInstanceDivisor = function () {
  29496. return this._instanceDivisor;
  29497. };
  29498. // Methods
  29499. /**
  29500. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29501. * Returns the created WebGLBuffer.
  29502. */
  29503. VertexBuffer.prototype.create = function (data) {
  29504. return this._buffer.create(data);
  29505. };
  29506. /**
  29507. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29508. * This function will create a new buffer if the current one is not updatable
  29509. * Returns the updated WebGLBuffer.
  29510. */
  29511. VertexBuffer.prototype.update = function (data) {
  29512. return this._buffer.update(data);
  29513. };
  29514. /**
  29515. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29516. * Returns the directly updated WebGLBuffer.
  29517. * @param data the new data
  29518. * @param offset the new offset
  29519. * @param useBytes set to true if the offset is in bytes
  29520. */
  29521. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29522. if (useBytes === void 0) { useBytes = false; }
  29523. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29524. };
  29525. /**
  29526. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29527. */
  29528. VertexBuffer.prototype.dispose = function () {
  29529. if (this._ownsBuffer) {
  29530. this._buffer.dispose();
  29531. }
  29532. };
  29533. /**
  29534. * Enumerates each value of this vertex buffer as numbers.
  29535. * @param count the number of values to enumerate
  29536. * @param callback the callback function called for each value
  29537. */
  29538. VertexBuffer.prototype.forEach = function (count, callback) {
  29539. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29540. };
  29541. Object.defineProperty(VertexBuffer, "PositionKind", {
  29542. get: function () {
  29543. return VertexBuffer._PositionKind;
  29544. },
  29545. enumerable: true,
  29546. configurable: true
  29547. });
  29548. Object.defineProperty(VertexBuffer, "NormalKind", {
  29549. get: function () {
  29550. return VertexBuffer._NormalKind;
  29551. },
  29552. enumerable: true,
  29553. configurable: true
  29554. });
  29555. Object.defineProperty(VertexBuffer, "TangentKind", {
  29556. get: function () {
  29557. return VertexBuffer._TangentKind;
  29558. },
  29559. enumerable: true,
  29560. configurable: true
  29561. });
  29562. Object.defineProperty(VertexBuffer, "UVKind", {
  29563. get: function () {
  29564. return VertexBuffer._UVKind;
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29570. get: function () {
  29571. return VertexBuffer._UV2Kind;
  29572. },
  29573. enumerable: true,
  29574. configurable: true
  29575. });
  29576. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29577. get: function () {
  29578. return VertexBuffer._UV3Kind;
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29584. get: function () {
  29585. return VertexBuffer._UV4Kind;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29591. get: function () {
  29592. return VertexBuffer._UV5Kind;
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29598. get: function () {
  29599. return VertexBuffer._UV6Kind;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. Object.defineProperty(VertexBuffer, "ColorKind", {
  29605. get: function () {
  29606. return VertexBuffer._ColorKind;
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29612. get: function () {
  29613. return VertexBuffer._MatricesIndicesKind;
  29614. },
  29615. enumerable: true,
  29616. configurable: true
  29617. });
  29618. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29619. get: function () {
  29620. return VertexBuffer._MatricesWeightsKind;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29626. get: function () {
  29627. return VertexBuffer._MatricesIndicesExtraKind;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29633. get: function () {
  29634. return VertexBuffer._MatricesWeightsExtraKind;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. /**
  29640. * Deduces the stride given a kind.
  29641. * @param kind The kind string to deduce
  29642. * @returns The deduced stride
  29643. */
  29644. VertexBuffer.DeduceStride = function (kind) {
  29645. switch (kind) {
  29646. case VertexBuffer.UVKind:
  29647. case VertexBuffer.UV2Kind:
  29648. case VertexBuffer.UV3Kind:
  29649. case VertexBuffer.UV4Kind:
  29650. case VertexBuffer.UV5Kind:
  29651. case VertexBuffer.UV6Kind:
  29652. return 2;
  29653. case VertexBuffer.NormalKind:
  29654. case VertexBuffer.PositionKind:
  29655. return 3;
  29656. case VertexBuffer.ColorKind:
  29657. case VertexBuffer.MatricesIndicesKind:
  29658. case VertexBuffer.MatricesIndicesExtraKind:
  29659. case VertexBuffer.MatricesWeightsKind:
  29660. case VertexBuffer.MatricesWeightsExtraKind:
  29661. case VertexBuffer.TangentKind:
  29662. return 4;
  29663. default:
  29664. throw new Error("Invalid kind '" + kind + "'");
  29665. }
  29666. };
  29667. /**
  29668. * Gets the byte length of the given type.
  29669. * @param type the type
  29670. * @returns the number of bytes
  29671. */
  29672. VertexBuffer.GetTypeByteLength = function (type) {
  29673. switch (type) {
  29674. case VertexBuffer.BYTE:
  29675. case VertexBuffer.UNSIGNED_BYTE:
  29676. return 1;
  29677. case VertexBuffer.SHORT:
  29678. case VertexBuffer.UNSIGNED_SHORT:
  29679. return 2;
  29680. case VertexBuffer.INT:
  29681. case VertexBuffer.FLOAT:
  29682. return 4;
  29683. default:
  29684. throw new Error("Invalid type '" + type + "'");
  29685. }
  29686. };
  29687. /**
  29688. * Enumerates each value of the given parameters as numbers.
  29689. * @param data the data to enumerate
  29690. * @param byteOffset the byte offset of the data
  29691. * @param byteStride the byte stride of the data
  29692. * @param componentCount the number of components per element
  29693. * @param componentType the type of the component
  29694. * @param count the total number of components
  29695. * @param normalized whether the data is normalized
  29696. * @param callback the callback function called for each value
  29697. */
  29698. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29699. if (data instanceof Array) {
  29700. var offset = byteOffset / 4;
  29701. var stride = byteStride / 4;
  29702. for (var index = 0; index < count; index += componentCount) {
  29703. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29704. callback(data[offset + componentIndex], index + componentIndex);
  29705. }
  29706. offset += stride;
  29707. }
  29708. }
  29709. else {
  29710. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29711. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29712. for (var index = 0; index < count; index += componentCount) {
  29713. var componentByteOffset = byteOffset;
  29714. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29715. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29716. callback(value, index + componentIndex);
  29717. componentByteOffset += componentByteLength;
  29718. }
  29719. byteOffset += byteStride;
  29720. }
  29721. }
  29722. };
  29723. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29724. switch (type) {
  29725. case VertexBuffer.BYTE: {
  29726. var value = dataView.getInt8(byteOffset);
  29727. if (normalized) {
  29728. value = Math.max(value / 127, -1);
  29729. }
  29730. return value;
  29731. }
  29732. case VertexBuffer.UNSIGNED_BYTE: {
  29733. var value = dataView.getUint8(byteOffset);
  29734. if (normalized) {
  29735. value = value / 255;
  29736. }
  29737. return value;
  29738. }
  29739. case VertexBuffer.SHORT: {
  29740. var value = dataView.getInt16(byteOffset, true);
  29741. if (normalized) {
  29742. value = Math.max(value / 16383, -1);
  29743. }
  29744. return value;
  29745. }
  29746. case VertexBuffer.UNSIGNED_SHORT: {
  29747. var value = dataView.getUint16(byteOffset, true);
  29748. if (normalized) {
  29749. value = value / 65535;
  29750. }
  29751. return value;
  29752. }
  29753. case VertexBuffer.FLOAT: {
  29754. return dataView.getFloat32(byteOffset, true);
  29755. }
  29756. default: {
  29757. throw new Error("Invalid component type " + type);
  29758. }
  29759. }
  29760. };
  29761. /**
  29762. * The byte type.
  29763. */
  29764. VertexBuffer.BYTE = 5120;
  29765. /**
  29766. * The unsigned byte type.
  29767. */
  29768. VertexBuffer.UNSIGNED_BYTE = 5121;
  29769. /**
  29770. * The short type.
  29771. */
  29772. VertexBuffer.SHORT = 5122;
  29773. /**
  29774. * The unsigned short type.
  29775. */
  29776. VertexBuffer.UNSIGNED_SHORT = 5123;
  29777. /**
  29778. * The integer type.
  29779. */
  29780. VertexBuffer.INT = 5124;
  29781. /**
  29782. * The unsigned integer type.
  29783. */
  29784. VertexBuffer.UNSIGNED_INT = 5125;
  29785. /**
  29786. * The float type.
  29787. */
  29788. VertexBuffer.FLOAT = 5126;
  29789. // Enums
  29790. VertexBuffer._PositionKind = "position";
  29791. VertexBuffer._NormalKind = "normal";
  29792. VertexBuffer._TangentKind = "tangent";
  29793. VertexBuffer._UVKind = "uv";
  29794. VertexBuffer._UV2Kind = "uv2";
  29795. VertexBuffer._UV3Kind = "uv3";
  29796. VertexBuffer._UV4Kind = "uv4";
  29797. VertexBuffer._UV5Kind = "uv5";
  29798. VertexBuffer._UV6Kind = "uv6";
  29799. VertexBuffer._ColorKind = "color";
  29800. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29801. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29802. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29803. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29804. return VertexBuffer;
  29805. }());
  29806. BABYLON.VertexBuffer = VertexBuffer;
  29807. })(BABYLON || (BABYLON = {}));
  29808. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29809. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29810. var BABYLON;
  29811. (function (BABYLON) {
  29812. /**
  29813. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29814. */
  29815. var DummyInternalTextureTracker = /** @class */ (function () {
  29816. function DummyInternalTextureTracker() {
  29817. /**
  29818. * Gets or set the previous tracker in the list
  29819. */
  29820. this.previous = null;
  29821. /**
  29822. * Gets or set the next tracker in the list
  29823. */
  29824. this.next = null;
  29825. }
  29826. return DummyInternalTextureTracker;
  29827. }());
  29828. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29829. })(BABYLON || (BABYLON = {}));
  29830. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29831. var BABYLON;
  29832. (function (BABYLON) {
  29833. /**
  29834. * Class used to store data associated with WebGL texture data for the engine
  29835. * This class should not be used directly
  29836. */
  29837. var InternalTexture = /** @class */ (function () {
  29838. /**
  29839. * Creates a new InternalTexture
  29840. * @param engine defines the engine to use
  29841. * @param dataSource defines the type of data that will be used
  29842. */
  29843. function InternalTexture(engine, dataSource) {
  29844. /**
  29845. * Observable called when the texture is loaded
  29846. */
  29847. this.onLoadedObservable = new BABYLON.Observable();
  29848. /**
  29849. * Gets or set the previous tracker in the list
  29850. */
  29851. this.previous = null;
  29852. /**
  29853. * Gets or set the next tracker in the list
  29854. */
  29855. this.next = null;
  29856. // Private
  29857. /** @hidden */
  29858. this._initialSlot = -1;
  29859. /** @hidden */
  29860. this._designatedSlot = -1;
  29861. /** @hidden */
  29862. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29863. /** @hidden */
  29864. this._comparisonFunction = 0;
  29865. /** @hidden */
  29866. this._sphericalPolynomial = null;
  29867. /** @hidden */
  29868. this._lodGenerationScale = 0;
  29869. /** @hidden */
  29870. this._lodGenerationOffset = 0;
  29871. /** @hidden */
  29872. this._isRGBD = false;
  29873. /** @hidden */
  29874. this._references = 1;
  29875. this._engine = engine;
  29876. this._dataSource = dataSource;
  29877. this._webGLTexture = engine._createTexture();
  29878. }
  29879. /**
  29880. * Gets the Engine the texture belongs to.
  29881. * @returns The babylon engine
  29882. */
  29883. InternalTexture.prototype.getEngine = function () {
  29884. return this._engine;
  29885. };
  29886. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29887. /**
  29888. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29889. */
  29890. get: function () {
  29891. return this._dataSource;
  29892. },
  29893. enumerable: true,
  29894. configurable: true
  29895. });
  29896. /**
  29897. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29898. */
  29899. InternalTexture.prototype.incrementReferences = function () {
  29900. this._references++;
  29901. };
  29902. /**
  29903. * Change the size of the texture (not the size of the content)
  29904. * @param width defines the new width
  29905. * @param height defines the new height
  29906. * @param depth defines the new depth (1 by default)
  29907. */
  29908. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29909. if (depth === void 0) { depth = 1; }
  29910. this.width = width;
  29911. this.height = height;
  29912. this.depth = depth;
  29913. this.baseWidth = width;
  29914. this.baseHeight = height;
  29915. this.baseDepth = depth;
  29916. this._size = width * height * depth;
  29917. };
  29918. /** @hidden */
  29919. InternalTexture.prototype._rebuild = function () {
  29920. var _this = this;
  29921. var proxy;
  29922. this.isReady = false;
  29923. this._cachedCoordinatesMode = null;
  29924. this._cachedWrapU = null;
  29925. this._cachedWrapV = null;
  29926. this._cachedAnisotropicFilteringLevel = null;
  29927. switch (this._dataSource) {
  29928. case InternalTexture.DATASOURCE_TEMP:
  29929. return;
  29930. case InternalTexture.DATASOURCE_URL:
  29931. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29932. _this.isReady = true;
  29933. }, null, this._buffer, undefined, this.format);
  29934. proxy._swapAndDie(this);
  29935. return;
  29936. case InternalTexture.DATASOURCE_RAW:
  29937. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29938. proxy._swapAndDie(this);
  29939. this.isReady = true;
  29940. return;
  29941. case InternalTexture.DATASOURCE_RAW3D:
  29942. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29943. proxy._swapAndDie(this);
  29944. this.isReady = true;
  29945. return;
  29946. case InternalTexture.DATASOURCE_DYNAMIC:
  29947. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29948. proxy._swapAndDie(this);
  29949. // The engine will make sure to update content so no need to flag it as isReady = true
  29950. return;
  29951. case InternalTexture.DATASOURCE_RENDERTARGET:
  29952. var options = new BABYLON.RenderTargetCreationOptions();
  29953. options.generateDepthBuffer = this._generateDepthBuffer;
  29954. options.generateMipMaps = this.generateMipMaps;
  29955. options.generateStencilBuffer = this._generateStencilBuffer;
  29956. options.samplingMode = this.samplingMode;
  29957. options.type = this.type;
  29958. if (this.isCube) {
  29959. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29960. }
  29961. else {
  29962. var size = {
  29963. width: this.width,
  29964. height: this.height
  29965. };
  29966. proxy = this._engine.createRenderTargetTexture(size, options);
  29967. }
  29968. proxy._swapAndDie(this);
  29969. this.isReady = true;
  29970. return;
  29971. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29972. var depthTextureOptions = {
  29973. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29974. comparisonFunction: this._comparisonFunction,
  29975. generateStencil: this._generateStencilBuffer,
  29976. isCube: this.isCube
  29977. };
  29978. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29979. proxy._swapAndDie(this);
  29980. this.isReady = true;
  29981. return;
  29982. case InternalTexture.DATASOURCE_CUBE:
  29983. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29984. _this.isReady = true;
  29985. }, null, this.format, this._extension);
  29986. proxy._swapAndDie(this);
  29987. return;
  29988. case InternalTexture.DATASOURCE_CUBERAW:
  29989. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29990. proxy._swapAndDie(this);
  29991. this.isReady = true;
  29992. return;
  29993. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29994. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29995. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29996. _this.isReady = true;
  29997. });
  29998. proxy._swapAndDie(this);
  29999. return;
  30000. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30001. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30002. if (proxy) {
  30003. proxy._swapAndDie(_this);
  30004. }
  30005. _this.isReady = true;
  30006. }, null, this.format, this._extension);
  30007. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30008. return;
  30009. }
  30010. };
  30011. /** @hidden */
  30012. InternalTexture.prototype._swapAndDie = function (target) {
  30013. target._webGLTexture = this._webGLTexture;
  30014. if (this._framebuffer) {
  30015. target._framebuffer = this._framebuffer;
  30016. }
  30017. if (this._depthStencilBuffer) {
  30018. target._depthStencilBuffer = this._depthStencilBuffer;
  30019. }
  30020. if (this._lodTextureHigh) {
  30021. if (target._lodTextureHigh) {
  30022. target._lodTextureHigh.dispose();
  30023. }
  30024. target._lodTextureHigh = this._lodTextureHigh;
  30025. }
  30026. if (this._lodTextureMid) {
  30027. if (target._lodTextureMid) {
  30028. target._lodTextureMid.dispose();
  30029. }
  30030. target._lodTextureMid = this._lodTextureMid;
  30031. }
  30032. if (this._lodTextureLow) {
  30033. if (target._lodTextureLow) {
  30034. target._lodTextureLow.dispose();
  30035. }
  30036. target._lodTextureLow = this._lodTextureLow;
  30037. }
  30038. var cache = this._engine.getLoadedTexturesCache();
  30039. var index = cache.indexOf(this);
  30040. if (index !== -1) {
  30041. cache.splice(index, 1);
  30042. }
  30043. };
  30044. /**
  30045. * Dispose the current allocated resources
  30046. */
  30047. InternalTexture.prototype.dispose = function () {
  30048. if (!this._webGLTexture) {
  30049. return;
  30050. }
  30051. this._references--;
  30052. if (this._references === 0) {
  30053. this._engine._releaseTexture(this);
  30054. this._webGLTexture = null;
  30055. this.previous = null;
  30056. this.next = null;
  30057. }
  30058. };
  30059. /**
  30060. * The source of the texture data is unknown
  30061. */
  30062. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30063. /**
  30064. * Texture data comes from an URL
  30065. */
  30066. InternalTexture.DATASOURCE_URL = 1;
  30067. /**
  30068. * Texture data is only used for temporary storage
  30069. */
  30070. InternalTexture.DATASOURCE_TEMP = 2;
  30071. /**
  30072. * Texture data comes from raw data (ArrayBuffer)
  30073. */
  30074. InternalTexture.DATASOURCE_RAW = 3;
  30075. /**
  30076. * Texture content is dynamic (video or dynamic texture)
  30077. */
  30078. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30079. /**
  30080. * Texture content is generated by rendering to it
  30081. */
  30082. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30083. /**
  30084. * Texture content is part of a multi render target process
  30085. */
  30086. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30087. /**
  30088. * Texture data comes from a cube data file
  30089. */
  30090. InternalTexture.DATASOURCE_CUBE = 7;
  30091. /**
  30092. * Texture data comes from a raw cube data
  30093. */
  30094. InternalTexture.DATASOURCE_CUBERAW = 8;
  30095. /**
  30096. * Texture data come from a prefiltered cube data file
  30097. */
  30098. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30099. /**
  30100. * Texture content is raw 3D data
  30101. */
  30102. InternalTexture.DATASOURCE_RAW3D = 10;
  30103. /**
  30104. * Texture content is a depth texture
  30105. */
  30106. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30107. /**
  30108. * Texture data comes from a raw cube data encoded with RGBD
  30109. */
  30110. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30111. return InternalTexture;
  30112. }());
  30113. BABYLON.InternalTexture = InternalTexture;
  30114. })(BABYLON || (BABYLON = {}));
  30115. //# sourceMappingURL=babylon.internalTexture.js.map
  30116. var BABYLON;
  30117. (function (BABYLON) {
  30118. var BaseTexture = /** @class */ (function () {
  30119. function BaseTexture(scene) {
  30120. this._hasAlpha = false;
  30121. this.getAlphaFromRGB = false;
  30122. this.level = 1;
  30123. this.coordinatesIndex = 0;
  30124. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30125. /**
  30126. * | Value | Type | Description |
  30127. * | ----- | ------------------ | ----------- |
  30128. * | 0 | CLAMP_ADDRESSMODE | |
  30129. * | 1 | WRAP_ADDRESSMODE | |
  30130. * | 2 | MIRROR_ADDRESSMODE | |
  30131. */
  30132. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30133. /**
  30134. * | Value | Type | Description |
  30135. * | ----- | ------------------ | ----------- |
  30136. * | 0 | CLAMP_ADDRESSMODE | |
  30137. * | 1 | WRAP_ADDRESSMODE | |
  30138. * | 2 | MIRROR_ADDRESSMODE | |
  30139. */
  30140. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30141. /**
  30142. * | Value | Type | Description |
  30143. * | ----- | ------------------ | ----------- |
  30144. * | 0 | CLAMP_ADDRESSMODE | |
  30145. * | 1 | WRAP_ADDRESSMODE | |
  30146. * | 2 | MIRROR_ADDRESSMODE | |
  30147. */
  30148. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30149. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30150. this.isCube = false;
  30151. this.is3D = false;
  30152. this.gammaSpace = true;
  30153. this.invertZ = false;
  30154. this.lodLevelInAlpha = false;
  30155. this.isRenderTarget = false;
  30156. this.animations = new Array();
  30157. /**
  30158. * An event triggered when the texture is disposed.
  30159. */
  30160. this.onDisposeObservable = new BABYLON.Observable();
  30161. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30162. this._cachedSize = BABYLON.Size.Zero();
  30163. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30164. if (this._scene) {
  30165. this._scene.textures.push(this);
  30166. }
  30167. this._uid = null;
  30168. }
  30169. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30170. get: function () {
  30171. return this._hasAlpha;
  30172. },
  30173. set: function (value) {
  30174. if (this._hasAlpha === value) {
  30175. return;
  30176. }
  30177. this._hasAlpha = value;
  30178. if (this._scene) {
  30179. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30180. }
  30181. },
  30182. enumerable: true,
  30183. configurable: true
  30184. });
  30185. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30186. get: function () {
  30187. return this._coordinatesMode;
  30188. },
  30189. /**
  30190. * How a texture is mapped.
  30191. *
  30192. * | Value | Type | Description |
  30193. * | ----- | ----------------------------------- | ----------- |
  30194. * | 0 | EXPLICIT_MODE | |
  30195. * | 1 | SPHERICAL_MODE | |
  30196. * | 2 | PLANAR_MODE | |
  30197. * | 3 | CUBIC_MODE | |
  30198. * | 4 | PROJECTION_MODE | |
  30199. * | 5 | SKYBOX_MODE | |
  30200. * | 6 | INVCUBIC_MODE | |
  30201. * | 7 | EQUIRECTANGULAR_MODE | |
  30202. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30203. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30204. */
  30205. set: function (value) {
  30206. if (this._coordinatesMode === value) {
  30207. return;
  30208. }
  30209. this._coordinatesMode = value;
  30210. if (this._scene) {
  30211. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30212. }
  30213. },
  30214. enumerable: true,
  30215. configurable: true
  30216. });
  30217. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30218. /**
  30219. * Gets whether or not the texture contains RGBD data.
  30220. */
  30221. get: function () {
  30222. return this._texture != null && this._texture._isRGBD;
  30223. },
  30224. enumerable: true,
  30225. configurable: true
  30226. });
  30227. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30228. get: function () {
  30229. if (this._texture)
  30230. return this._texture._lodGenerationOffset;
  30231. return 0.0;
  30232. },
  30233. set: function (value) {
  30234. if (this._texture)
  30235. this._texture._lodGenerationOffset = value;
  30236. },
  30237. enumerable: true,
  30238. configurable: true
  30239. });
  30240. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30241. get: function () {
  30242. if (this._texture)
  30243. return this._texture._lodGenerationScale;
  30244. return 0.0;
  30245. },
  30246. set: function (value) {
  30247. if (this._texture)
  30248. this._texture._lodGenerationScale = value;
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(BaseTexture.prototype, "uid", {
  30254. get: function () {
  30255. if (!this._uid) {
  30256. this._uid = BABYLON.Tools.RandomId();
  30257. }
  30258. return this._uid;
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. BaseTexture.prototype.toString = function () {
  30264. return this.name;
  30265. };
  30266. BaseTexture.prototype.getClassName = function () {
  30267. return "BaseTexture";
  30268. };
  30269. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30270. set: function (callback) {
  30271. if (this._onDisposeObserver) {
  30272. this.onDisposeObservable.remove(this._onDisposeObserver);
  30273. }
  30274. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30275. },
  30276. enumerable: true,
  30277. configurable: true
  30278. });
  30279. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30280. get: function () {
  30281. return true;
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. BaseTexture.prototype.getScene = function () {
  30287. return this._scene;
  30288. };
  30289. BaseTexture.prototype.getTextureMatrix = function () {
  30290. return BABYLON.Matrix.IdentityReadOnly;
  30291. };
  30292. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30293. return BABYLON.Matrix.IdentityReadOnly;
  30294. };
  30295. BaseTexture.prototype.getInternalTexture = function () {
  30296. return this._texture;
  30297. };
  30298. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30299. return !this.isBlocking || this.isReady();
  30300. };
  30301. BaseTexture.prototype.isReady = function () {
  30302. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30303. this.delayLoad();
  30304. return false;
  30305. }
  30306. if (this._texture) {
  30307. return this._texture.isReady;
  30308. }
  30309. return false;
  30310. };
  30311. BaseTexture.prototype.getSize = function () {
  30312. if (this._texture) {
  30313. if (this._texture.width) {
  30314. this._cachedSize.width = this._texture.width;
  30315. this._cachedSize.height = this._texture.height;
  30316. return this._cachedSize;
  30317. }
  30318. if (this._texture._size) {
  30319. this._cachedSize.width = this._texture._size;
  30320. this._cachedSize.height = this._texture._size;
  30321. return this._cachedSize;
  30322. }
  30323. }
  30324. return this._cachedSize;
  30325. };
  30326. BaseTexture.prototype.getBaseSize = function () {
  30327. if (!this.isReady() || !this._texture)
  30328. return BABYLON.Size.Zero();
  30329. if (this._texture._size) {
  30330. return new BABYLON.Size(this._texture._size, this._texture._size);
  30331. }
  30332. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30333. };
  30334. BaseTexture.prototype.scale = function (ratio) {
  30335. };
  30336. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30337. get: function () {
  30338. return false;
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. /** @hidden */
  30344. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30345. if (!this._scene) {
  30346. return null;
  30347. }
  30348. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30349. for (var index = 0; index < texturesCache.length; index++) {
  30350. var texturesCacheEntry = texturesCache[index];
  30351. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30352. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30353. texturesCacheEntry.incrementReferences();
  30354. return texturesCacheEntry;
  30355. }
  30356. }
  30357. }
  30358. return null;
  30359. };
  30360. /** @hidden */
  30361. BaseTexture.prototype._rebuild = function () {
  30362. };
  30363. BaseTexture.prototype.delayLoad = function () {
  30364. };
  30365. BaseTexture.prototype.clone = function () {
  30366. return null;
  30367. };
  30368. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30369. get: function () {
  30370. if (!this._texture) {
  30371. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30372. }
  30373. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30374. },
  30375. enumerable: true,
  30376. configurable: true
  30377. });
  30378. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30379. get: function () {
  30380. if (!this._texture) {
  30381. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30382. }
  30383. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30384. },
  30385. enumerable: true,
  30386. configurable: true
  30387. });
  30388. /**
  30389. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30390. * This will returns an RGBA array buffer containing either in values (0-255) or
  30391. * float values (0-1) depending of the underlying buffer type.
  30392. * @param faceIndex The face of the texture to read (in case of cube texture)
  30393. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30394. * @returns The Array buffer containing the pixels data.
  30395. */
  30396. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30397. if (faceIndex === void 0) { faceIndex = 0; }
  30398. if (level === void 0) { level = 0; }
  30399. if (!this._texture) {
  30400. return null;
  30401. }
  30402. var size = this.getSize();
  30403. var width = size.width;
  30404. var height = size.height;
  30405. var scene = this.getScene();
  30406. if (!scene) {
  30407. return null;
  30408. }
  30409. var engine = scene.getEngine();
  30410. if (level != 0) {
  30411. width = width / Math.pow(2, level);
  30412. height = height / Math.pow(2, level);
  30413. width = Math.round(width);
  30414. height = Math.round(height);
  30415. }
  30416. if (this._texture.isCube) {
  30417. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30418. }
  30419. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30420. };
  30421. BaseTexture.prototype.releaseInternalTexture = function () {
  30422. if (this._texture) {
  30423. this._texture.dispose();
  30424. this._texture = null;
  30425. }
  30426. };
  30427. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30428. get: function () {
  30429. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30430. return null;
  30431. }
  30432. if (!this._texture._sphericalPolynomial) {
  30433. this._texture._sphericalPolynomial =
  30434. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30435. }
  30436. return this._texture._sphericalPolynomial;
  30437. },
  30438. set: function (value) {
  30439. if (this._texture) {
  30440. this._texture._sphericalPolynomial = value;
  30441. }
  30442. },
  30443. enumerable: true,
  30444. configurable: true
  30445. });
  30446. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30447. get: function () {
  30448. if (this._texture) {
  30449. return this._texture._lodTextureHigh;
  30450. }
  30451. return null;
  30452. },
  30453. enumerable: true,
  30454. configurable: true
  30455. });
  30456. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30457. get: function () {
  30458. if (this._texture) {
  30459. return this._texture._lodTextureMid;
  30460. }
  30461. return null;
  30462. },
  30463. enumerable: true,
  30464. configurable: true
  30465. });
  30466. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30467. get: function () {
  30468. if (this._texture) {
  30469. return this._texture._lodTextureLow;
  30470. }
  30471. return null;
  30472. },
  30473. enumerable: true,
  30474. configurable: true
  30475. });
  30476. BaseTexture.prototype.dispose = function () {
  30477. if (!this._scene) {
  30478. return;
  30479. }
  30480. // Animations
  30481. this._scene.stopAnimation(this);
  30482. // Remove from scene
  30483. this._scene._removePendingData(this);
  30484. var index = this._scene.textures.indexOf(this);
  30485. if (index >= 0) {
  30486. this._scene.textures.splice(index, 1);
  30487. }
  30488. if (this._texture === undefined) {
  30489. return;
  30490. }
  30491. // Release
  30492. this.releaseInternalTexture();
  30493. // Callback
  30494. this.onDisposeObservable.notifyObservers(this);
  30495. this.onDisposeObservable.clear();
  30496. };
  30497. BaseTexture.prototype.serialize = function () {
  30498. if (!this.name) {
  30499. return null;
  30500. }
  30501. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30502. // Animations
  30503. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30504. return serializationObject;
  30505. };
  30506. BaseTexture.WhenAllReady = function (textures, callback) {
  30507. var numRemaining = textures.length;
  30508. if (numRemaining === 0) {
  30509. callback();
  30510. return;
  30511. }
  30512. var _loop_1 = function () {
  30513. texture = textures[i];
  30514. if (texture.isReady()) {
  30515. if (--numRemaining === 0) {
  30516. callback();
  30517. }
  30518. }
  30519. else {
  30520. onLoadObservable = texture.onLoadObservable;
  30521. var onLoadCallback_1 = function () {
  30522. onLoadObservable.removeCallback(onLoadCallback_1);
  30523. if (--numRemaining === 0) {
  30524. callback();
  30525. }
  30526. };
  30527. onLoadObservable.add(onLoadCallback_1);
  30528. }
  30529. };
  30530. var texture, onLoadObservable;
  30531. for (var i = 0; i < textures.length; i++) {
  30532. _loop_1();
  30533. }
  30534. };
  30535. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30536. __decorate([
  30537. BABYLON.serialize()
  30538. ], BaseTexture.prototype, "name", void 0);
  30539. __decorate([
  30540. BABYLON.serialize("hasAlpha")
  30541. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30542. __decorate([
  30543. BABYLON.serialize()
  30544. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30545. __decorate([
  30546. BABYLON.serialize()
  30547. ], BaseTexture.prototype, "level", void 0);
  30548. __decorate([
  30549. BABYLON.serialize()
  30550. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30551. __decorate([
  30552. BABYLON.serialize("coordinatesMode")
  30553. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30554. __decorate([
  30555. BABYLON.serialize()
  30556. ], BaseTexture.prototype, "wrapU", void 0);
  30557. __decorate([
  30558. BABYLON.serialize()
  30559. ], BaseTexture.prototype, "wrapV", void 0);
  30560. __decorate([
  30561. BABYLON.serialize()
  30562. ], BaseTexture.prototype, "wrapR", void 0);
  30563. __decorate([
  30564. BABYLON.serialize()
  30565. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30566. __decorate([
  30567. BABYLON.serialize()
  30568. ], BaseTexture.prototype, "isCube", void 0);
  30569. __decorate([
  30570. BABYLON.serialize()
  30571. ], BaseTexture.prototype, "is3D", void 0);
  30572. __decorate([
  30573. BABYLON.serialize()
  30574. ], BaseTexture.prototype, "gammaSpace", void 0);
  30575. __decorate([
  30576. BABYLON.serialize()
  30577. ], BaseTexture.prototype, "invertZ", void 0);
  30578. __decorate([
  30579. BABYLON.serialize()
  30580. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30581. __decorate([
  30582. BABYLON.serialize()
  30583. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30584. __decorate([
  30585. BABYLON.serialize()
  30586. ], BaseTexture.prototype, "lodGenerationScale", null);
  30587. __decorate([
  30588. BABYLON.serialize()
  30589. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30590. return BaseTexture;
  30591. }());
  30592. BABYLON.BaseTexture = BaseTexture;
  30593. })(BABYLON || (BABYLON = {}));
  30594. //# sourceMappingURL=babylon.baseTexture.js.map
  30595. var BABYLON;
  30596. (function (BABYLON) {
  30597. var Texture = /** @class */ (function (_super) {
  30598. __extends(Texture, _super);
  30599. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30600. if (noMipmap === void 0) { noMipmap = false; }
  30601. if (invertY === void 0) { invertY = true; }
  30602. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30603. if (onLoad === void 0) { onLoad = null; }
  30604. if (onError === void 0) { onError = null; }
  30605. if (buffer === void 0) { buffer = null; }
  30606. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30607. var _this = _super.call(this, scene) || this;
  30608. _this.uOffset = 0;
  30609. _this.vOffset = 0;
  30610. _this.uScale = 1.0;
  30611. _this.vScale = 1.0;
  30612. _this.uAng = 0;
  30613. _this.vAng = 0;
  30614. _this.wAng = 0;
  30615. /**
  30616. * Defines the center of rotation (U)
  30617. */
  30618. _this.uRotationCenter = 0.5;
  30619. /**
  30620. * Defines the center of rotation (V)
  30621. */
  30622. _this.vRotationCenter = 0.5;
  30623. /**
  30624. * Defines the center of rotation (W)
  30625. */
  30626. _this.wRotationCenter = 0.5;
  30627. _this._isBlocking = true;
  30628. _this.name = url || "";
  30629. _this.url = url;
  30630. _this._noMipmap = noMipmap;
  30631. _this._invertY = invertY;
  30632. _this._samplingMode = samplingMode;
  30633. _this._buffer = buffer;
  30634. _this._deleteBuffer = deleteBuffer;
  30635. if (format) {
  30636. _this._format = format;
  30637. }
  30638. scene = _this.getScene();
  30639. if (!scene) {
  30640. return _this;
  30641. }
  30642. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30643. var load = function () {
  30644. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30645. _this.onLoadObservable.notifyObservers(_this);
  30646. }
  30647. if (onLoad) {
  30648. onLoad();
  30649. }
  30650. if (!_this.isBlocking && scene) {
  30651. scene.resetCachedMaterial();
  30652. }
  30653. };
  30654. if (!_this.url) {
  30655. _this._delayedOnLoad = load;
  30656. _this._delayedOnError = onError;
  30657. return _this;
  30658. }
  30659. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30660. if (!_this._texture) {
  30661. if (!scene.useDelayedTextureLoading) {
  30662. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30663. if (deleteBuffer) {
  30664. delete _this._buffer;
  30665. }
  30666. }
  30667. else {
  30668. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30669. _this._delayedOnLoad = load;
  30670. _this._delayedOnError = onError;
  30671. }
  30672. }
  30673. else {
  30674. if (_this._texture.isReady) {
  30675. BABYLON.Tools.SetImmediate(function () { return load(); });
  30676. }
  30677. else {
  30678. _this._texture.onLoadedObservable.add(load);
  30679. }
  30680. }
  30681. return _this;
  30682. }
  30683. Object.defineProperty(Texture.prototype, "noMipmap", {
  30684. get: function () {
  30685. return this._noMipmap;
  30686. },
  30687. enumerable: true,
  30688. configurable: true
  30689. });
  30690. Object.defineProperty(Texture.prototype, "isBlocking", {
  30691. get: function () {
  30692. return this._isBlocking;
  30693. },
  30694. set: function (value) {
  30695. this._isBlocking = value;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. Object.defineProperty(Texture.prototype, "samplingMode", {
  30701. get: function () {
  30702. return this._samplingMode;
  30703. },
  30704. enumerable: true,
  30705. configurable: true
  30706. });
  30707. /**
  30708. * Update the url (and optional buffer) of this texture if url was null during construction.
  30709. * @param url the url of the texture
  30710. * @param buffer the buffer of the texture (defaults to null)
  30711. */
  30712. Texture.prototype.updateURL = function (url, buffer) {
  30713. if (buffer === void 0) { buffer = null; }
  30714. if (this.url) {
  30715. throw new Error("URL is already set");
  30716. }
  30717. this.url = url;
  30718. this._buffer = buffer;
  30719. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30720. this.delayLoad();
  30721. };
  30722. Texture.prototype.delayLoad = function () {
  30723. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30724. return;
  30725. }
  30726. var scene = this.getScene();
  30727. if (!scene) {
  30728. return;
  30729. }
  30730. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30731. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30732. if (!this._texture) {
  30733. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30734. if (this._deleteBuffer) {
  30735. delete this._buffer;
  30736. }
  30737. }
  30738. else {
  30739. if (this._delayedOnLoad) {
  30740. if (this._texture.isReady) {
  30741. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30742. }
  30743. else {
  30744. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30745. }
  30746. }
  30747. }
  30748. this._delayedOnLoad = null;
  30749. this._delayedOnError = null;
  30750. };
  30751. /**
  30752. * Default is Trilinear mode.
  30753. *
  30754. * | Value | Type | Description |
  30755. * | ----- | ------------------ | ----------- |
  30756. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30757. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30758. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30759. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30760. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30761. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30762. * | 7 | NEAREST_LINEAR | |
  30763. * | 8 | NEAREST_NEAREST | |
  30764. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30765. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30766. * | 11 | LINEAR_LINEAR | |
  30767. * | 12 | LINEAR_NEAREST | |
  30768. *
  30769. * > _mag_: magnification filter (close to the viewer)
  30770. * > _min_: minification filter (far from the viewer)
  30771. * > _mip_: filter used between mip map levels
  30772. *
  30773. */
  30774. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30775. if (!this._texture) {
  30776. return;
  30777. }
  30778. var scene = this.getScene();
  30779. if (!scene) {
  30780. return;
  30781. }
  30782. this._samplingMode = samplingMode;
  30783. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30784. };
  30785. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30786. x *= this.uScale;
  30787. y *= this.vScale;
  30788. x -= this.uRotationCenter * this.uScale;
  30789. y -= this.vRotationCenter * this.vScale;
  30790. z -= this.wRotationCenter;
  30791. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30792. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30793. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30794. t.z += this.wRotationCenter;
  30795. };
  30796. Texture.prototype.getTextureMatrix = function () {
  30797. var _this = this;
  30798. if (this.uOffset === this._cachedUOffset &&
  30799. this.vOffset === this._cachedVOffset &&
  30800. this.uScale === this._cachedUScale &&
  30801. this.vScale === this._cachedVScale &&
  30802. this.uAng === this._cachedUAng &&
  30803. this.vAng === this._cachedVAng &&
  30804. this.wAng === this._cachedWAng) {
  30805. return this._cachedTextureMatrix;
  30806. }
  30807. this._cachedUOffset = this.uOffset;
  30808. this._cachedVOffset = this.vOffset;
  30809. this._cachedUScale = this.uScale;
  30810. this._cachedVScale = this.vScale;
  30811. this._cachedUAng = this.uAng;
  30812. this._cachedVAng = this.vAng;
  30813. this._cachedWAng = this.wAng;
  30814. if (!this._cachedTextureMatrix) {
  30815. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30816. this._rowGenerationMatrix = new BABYLON.Matrix();
  30817. this._t0 = BABYLON.Vector3.Zero();
  30818. this._t1 = BABYLON.Vector3.Zero();
  30819. this._t2 = BABYLON.Vector3.Zero();
  30820. }
  30821. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30822. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30823. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30824. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30825. this._t1.subtractInPlace(this._t0);
  30826. this._t2.subtractInPlace(this._t0);
  30827. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30828. this._cachedTextureMatrix.m[0] = this._t1.x;
  30829. this._cachedTextureMatrix.m[1] = this._t1.y;
  30830. this._cachedTextureMatrix.m[2] = this._t1.z;
  30831. this._cachedTextureMatrix.m[4] = this._t2.x;
  30832. this._cachedTextureMatrix.m[5] = this._t2.y;
  30833. this._cachedTextureMatrix.m[6] = this._t2.z;
  30834. this._cachedTextureMatrix.m[8] = this._t0.x;
  30835. this._cachedTextureMatrix.m[9] = this._t0.y;
  30836. this._cachedTextureMatrix.m[10] = this._t0.z;
  30837. var scene = this.getScene();
  30838. if (!scene) {
  30839. return this._cachedTextureMatrix;
  30840. }
  30841. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30842. return mat.hasTexture(_this);
  30843. });
  30844. return this._cachedTextureMatrix;
  30845. };
  30846. Texture.prototype.getReflectionTextureMatrix = function () {
  30847. var _this = this;
  30848. var scene = this.getScene();
  30849. if (!scene) {
  30850. return this._cachedTextureMatrix;
  30851. }
  30852. if (this.uOffset === this._cachedUOffset &&
  30853. this.vOffset === this._cachedVOffset &&
  30854. this.uScale === this._cachedUScale &&
  30855. this.vScale === this._cachedVScale &&
  30856. this.coordinatesMode === this._cachedCoordinatesMode) {
  30857. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30858. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30859. return this._cachedTextureMatrix;
  30860. }
  30861. }
  30862. else {
  30863. return this._cachedTextureMatrix;
  30864. }
  30865. }
  30866. if (!this._cachedTextureMatrix) {
  30867. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30868. }
  30869. if (!this._projectionModeMatrix) {
  30870. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30871. }
  30872. this._cachedUOffset = this.uOffset;
  30873. this._cachedVOffset = this.vOffset;
  30874. this._cachedUScale = this.uScale;
  30875. this._cachedVScale = this.vScale;
  30876. this._cachedCoordinatesMode = this.coordinatesMode;
  30877. switch (this.coordinatesMode) {
  30878. case Texture.PLANAR_MODE:
  30879. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30880. this._cachedTextureMatrix[0] = this.uScale;
  30881. this._cachedTextureMatrix[5] = this.vScale;
  30882. this._cachedTextureMatrix[12] = this.uOffset;
  30883. this._cachedTextureMatrix[13] = this.vOffset;
  30884. break;
  30885. case Texture.PROJECTION_MODE:
  30886. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30887. this._projectionModeMatrix.m[0] = 0.5;
  30888. this._projectionModeMatrix.m[5] = -0.5;
  30889. this._projectionModeMatrix.m[10] = 0.0;
  30890. this._projectionModeMatrix.m[12] = 0.5;
  30891. this._projectionModeMatrix.m[13] = 0.5;
  30892. this._projectionModeMatrix.m[14] = 1.0;
  30893. this._projectionModeMatrix.m[15] = 1.0;
  30894. var projectionMatrix = scene.getProjectionMatrix();
  30895. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30896. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30897. break;
  30898. default:
  30899. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30900. break;
  30901. }
  30902. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30903. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30904. });
  30905. return this._cachedTextureMatrix;
  30906. };
  30907. Texture.prototype.clone = function () {
  30908. var _this = this;
  30909. return BABYLON.SerializationHelper.Clone(function () {
  30910. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30911. }, this);
  30912. };
  30913. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30914. get: function () {
  30915. if (!this._onLoadObservable) {
  30916. this._onLoadObservable = new BABYLON.Observable();
  30917. }
  30918. return this._onLoadObservable;
  30919. },
  30920. enumerable: true,
  30921. configurable: true
  30922. });
  30923. Texture.prototype.serialize = function () {
  30924. var serializationObject = _super.prototype.serialize.call(this);
  30925. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30926. serializationObject.base64String = this._buffer;
  30927. serializationObject.name = serializationObject.name.replace("data:", "");
  30928. }
  30929. serializationObject.invertY = this._invertY;
  30930. serializationObject.samplingMode = this.samplingMode;
  30931. return serializationObject;
  30932. };
  30933. Texture.prototype.getClassName = function () {
  30934. return "Texture";
  30935. };
  30936. Texture.prototype.dispose = function () {
  30937. _super.prototype.dispose.call(this);
  30938. if (this._onLoadObservable) {
  30939. this._onLoadObservable.clear();
  30940. this._onLoadObservable = null;
  30941. }
  30942. this._delayedOnLoad = null;
  30943. this._delayedOnError = null;
  30944. };
  30945. // Statics
  30946. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30947. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30948. if (onLoad === void 0) { onLoad = null; }
  30949. if (onError === void 0) { onError = null; }
  30950. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30951. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30952. };
  30953. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30954. if (parsedTexture.customType) {
  30955. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30956. // Update Sampling Mode
  30957. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30958. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30959. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30960. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30961. }
  30962. }
  30963. return parsedCustomTexture;
  30964. }
  30965. if (parsedTexture.isCube) {
  30966. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30967. }
  30968. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30969. return null;
  30970. }
  30971. var texture = BABYLON.SerializationHelper.Parse(function () {
  30972. var generateMipMaps = true;
  30973. if (parsedTexture.noMipmap) {
  30974. generateMipMaps = false;
  30975. }
  30976. if (parsedTexture.mirrorPlane) {
  30977. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30978. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30979. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30980. return mirrorTexture;
  30981. }
  30982. else if (parsedTexture.isRenderTarget) {
  30983. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30984. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30985. return renderTargetTexture;
  30986. }
  30987. else {
  30988. var texture;
  30989. if (parsedTexture.base64String) {
  30990. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30991. }
  30992. else {
  30993. var url = rootUrl + parsedTexture.name;
  30994. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30995. url = parsedTexture.url;
  30996. }
  30997. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30998. }
  30999. return texture;
  31000. }
  31001. }, parsedTexture, scene);
  31002. // Update Sampling Mode
  31003. if (parsedTexture.samplingMode) {
  31004. var sampling = parsedTexture.samplingMode;
  31005. if (texture._samplingMode !== sampling) {
  31006. texture.updateSamplingMode(sampling);
  31007. }
  31008. }
  31009. // Animations
  31010. if (parsedTexture.animations) {
  31011. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31012. var parsedAnimation = parsedTexture.animations[animationIndex];
  31013. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31014. }
  31015. }
  31016. return texture;
  31017. };
  31018. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31019. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31020. if (noMipmap === void 0) { noMipmap = false; }
  31021. if (invertY === void 0) { invertY = true; }
  31022. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31023. if (onLoad === void 0) { onLoad = null; }
  31024. if (onError === void 0) { onError = null; }
  31025. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31026. if (name.substr(0, 5) !== "data:") {
  31027. name = "data:" + name;
  31028. }
  31029. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31030. };
  31031. // Constants
  31032. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31033. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31034. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31035. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31036. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31037. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31038. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31039. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31040. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31041. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31042. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31043. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31044. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31045. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31046. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31047. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31048. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31049. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31050. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31051. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31052. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31053. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31054. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31055. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31056. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31057. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31058. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31059. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31060. /**
  31061. * 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
  31062. */
  31063. Texture.UseSerializedUrlIfAny = false;
  31064. __decorate([
  31065. BABYLON.serialize()
  31066. ], Texture.prototype, "url", void 0);
  31067. __decorate([
  31068. BABYLON.serialize()
  31069. ], Texture.prototype, "uOffset", void 0);
  31070. __decorate([
  31071. BABYLON.serialize()
  31072. ], Texture.prototype, "vOffset", void 0);
  31073. __decorate([
  31074. BABYLON.serialize()
  31075. ], Texture.prototype, "uScale", void 0);
  31076. __decorate([
  31077. BABYLON.serialize()
  31078. ], Texture.prototype, "vScale", void 0);
  31079. __decorate([
  31080. BABYLON.serialize()
  31081. ], Texture.prototype, "uAng", void 0);
  31082. __decorate([
  31083. BABYLON.serialize()
  31084. ], Texture.prototype, "vAng", void 0);
  31085. __decorate([
  31086. BABYLON.serialize()
  31087. ], Texture.prototype, "wAng", void 0);
  31088. __decorate([
  31089. BABYLON.serialize()
  31090. ], Texture.prototype, "uRotationCenter", void 0);
  31091. __decorate([
  31092. BABYLON.serialize()
  31093. ], Texture.prototype, "vRotationCenter", void 0);
  31094. __decorate([
  31095. BABYLON.serialize()
  31096. ], Texture.prototype, "wRotationCenter", void 0);
  31097. __decorate([
  31098. BABYLON.serialize()
  31099. ], Texture.prototype, "isBlocking", null);
  31100. return Texture;
  31101. }(BABYLON.BaseTexture));
  31102. BABYLON.Texture = Texture;
  31103. })(BABYLON || (BABYLON = {}));
  31104. //# sourceMappingURL=babylon.texture.js.map
  31105. var BABYLON;
  31106. (function (BABYLON) {
  31107. /**
  31108. * @hidden
  31109. **/
  31110. var _InstancesBatch = /** @class */ (function () {
  31111. function _InstancesBatch() {
  31112. this.mustReturn = false;
  31113. this.visibleInstances = new Array();
  31114. this.renderSelf = new Array();
  31115. }
  31116. return _InstancesBatch;
  31117. }());
  31118. BABYLON._InstancesBatch = _InstancesBatch;
  31119. var Mesh = /** @class */ (function (_super) {
  31120. __extends(Mesh, _super);
  31121. /**
  31122. * @constructor
  31123. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31124. * @param {Scene} scene The scene to add this mesh to.
  31125. * @param {Node} parent The parent of this mesh, if it has one
  31126. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31127. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31128. * When false, achieved by calling a clone(), also passing False.
  31129. * This will make creation of children, recursive.
  31130. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31131. */
  31132. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31133. if (scene === void 0) { scene = null; }
  31134. if (parent === void 0) { parent = null; }
  31135. if (source === void 0) { source = null; }
  31136. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31137. var _this = _super.call(this, name, scene) || this;
  31138. // Members
  31139. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31140. _this.instances = new Array();
  31141. _this._LODLevels = new Array();
  31142. /** @hidden */
  31143. _this._visibleInstances = {};
  31144. _this._renderIdForInstances = new Array();
  31145. _this._batchCache = new _InstancesBatch();
  31146. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31147. // Use by builder only to know what orientation were the mesh build in.
  31148. /** @hidden */
  31149. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31150. _this.overrideMaterialSideOrientation = null;
  31151. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31152. // Will be used to save a source mesh reference, If any
  31153. _this._source = null;
  31154. scene = _this.getScene();
  31155. if (source) {
  31156. // Geometry
  31157. if (source._geometry) {
  31158. source._geometry.applyToMesh(_this);
  31159. }
  31160. // Deep copy
  31161. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31162. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31163. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31164. ], ["_poseMatrix"]);
  31165. // Source mesh
  31166. _this._source = source;
  31167. // Construction Params
  31168. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31169. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31170. var myAnyThis = _this;
  31171. var myAnySource = source;
  31172. myAnyThis._closePath = myAnySource._closePath;
  31173. myAnyThis._idx = myAnySource._idx;
  31174. myAnyThis.dashSize = myAnySource.dashSize;
  31175. myAnyThis.gapSize = myAnySource.gapSize;
  31176. myAnyThis.path3D = myAnySource.path3D;
  31177. myAnyThis.pathArray = myAnySource.pathArray;
  31178. myAnyThis.arc = myAnySource.arc;
  31179. myAnyThis.radius = myAnySource.radius;
  31180. // Animation ranges
  31181. if (_this._source._ranges) {
  31182. var ranges = _this._source._ranges;
  31183. for (var name in ranges) {
  31184. if (!ranges.hasOwnProperty(name)) {
  31185. continue;
  31186. }
  31187. if (!ranges[name]) {
  31188. continue;
  31189. }
  31190. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31191. }
  31192. }
  31193. // Metadata
  31194. if (source.metadata && source.metadata.clone) {
  31195. _this.metadata = source.metadata.clone();
  31196. }
  31197. else {
  31198. _this.metadata = source.metadata;
  31199. }
  31200. // Tags
  31201. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31202. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31203. }
  31204. // Parent
  31205. _this.parent = source.parent;
  31206. // Pivot
  31207. _this.setPivotMatrix(source.getPivotMatrix());
  31208. _this.id = name + "." + source.id;
  31209. // Material
  31210. _this.material = source.material;
  31211. var index;
  31212. if (!doNotCloneChildren) {
  31213. // Children
  31214. var directDescendants = source.getDescendants(true);
  31215. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31216. var child = directDescendants[index_1];
  31217. if (child.clone) {
  31218. child.clone(name + "." + child.name, _this);
  31219. }
  31220. }
  31221. }
  31222. // Physics clone
  31223. var physicsEngine = _this.getScene().getPhysicsEngine();
  31224. if (clonePhysicsImpostor && physicsEngine) {
  31225. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31226. if (impostor) {
  31227. _this.physicsImpostor = impostor.clone(_this);
  31228. }
  31229. }
  31230. // Particles
  31231. for (index = 0; index < scene.particleSystems.length; index++) {
  31232. var system = scene.particleSystems[index];
  31233. if (system.emitter === source) {
  31234. system.clone(system.name, _this);
  31235. }
  31236. }
  31237. _this.refreshBoundingInfo();
  31238. _this.computeWorldMatrix(true);
  31239. }
  31240. // Parent
  31241. if (parent !== null) {
  31242. _this.parent = parent;
  31243. }
  31244. return _this;
  31245. }
  31246. Object.defineProperty(Mesh, "FRONTSIDE", {
  31247. /**
  31248. * Mesh side orientation : usually the external or front surface
  31249. */
  31250. get: function () {
  31251. return Mesh._FRONTSIDE;
  31252. },
  31253. enumerable: true,
  31254. configurable: true
  31255. });
  31256. Object.defineProperty(Mesh, "BACKSIDE", {
  31257. /**
  31258. * Mesh side orientation : usually the internal or back surface
  31259. */
  31260. get: function () {
  31261. return Mesh._BACKSIDE;
  31262. },
  31263. enumerable: true,
  31264. configurable: true
  31265. });
  31266. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31267. /**
  31268. * Mesh side orientation : both internal and external or front and back surfaces
  31269. */
  31270. get: function () {
  31271. return Mesh._DOUBLESIDE;
  31272. },
  31273. enumerable: true,
  31274. configurable: true
  31275. });
  31276. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31277. /**
  31278. * Mesh side orientation : by default, `FRONTSIDE`
  31279. */
  31280. get: function () {
  31281. return Mesh._DEFAULTSIDE;
  31282. },
  31283. enumerable: true,
  31284. configurable: true
  31285. });
  31286. Object.defineProperty(Mesh, "NO_CAP", {
  31287. /**
  31288. * Mesh cap setting : no cap
  31289. */
  31290. get: function () {
  31291. return Mesh._NO_CAP;
  31292. },
  31293. enumerable: true,
  31294. configurable: true
  31295. });
  31296. Object.defineProperty(Mesh, "CAP_START", {
  31297. /**
  31298. * Mesh cap setting : one cap at the beginning of the mesh
  31299. */
  31300. get: function () {
  31301. return Mesh._CAP_START;
  31302. },
  31303. enumerable: true,
  31304. configurable: true
  31305. });
  31306. Object.defineProperty(Mesh, "CAP_END", {
  31307. /**
  31308. * Mesh cap setting : one cap at the end of the mesh
  31309. */
  31310. get: function () {
  31311. return Mesh._CAP_END;
  31312. },
  31313. enumerable: true,
  31314. configurable: true
  31315. });
  31316. Object.defineProperty(Mesh, "CAP_ALL", {
  31317. /**
  31318. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31319. */
  31320. get: function () {
  31321. return Mesh._CAP_ALL;
  31322. },
  31323. enumerable: true,
  31324. configurable: true
  31325. });
  31326. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31327. /**
  31328. * An event triggered before rendering the mesh
  31329. */
  31330. get: function () {
  31331. if (!this._onBeforeRenderObservable) {
  31332. this._onBeforeRenderObservable = new BABYLON.Observable();
  31333. }
  31334. return this._onBeforeRenderObservable;
  31335. },
  31336. enumerable: true,
  31337. configurable: true
  31338. });
  31339. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31340. /**
  31341. * An event triggered after rendering the mesh
  31342. */
  31343. get: function () {
  31344. if (!this._onAfterRenderObservable) {
  31345. this._onAfterRenderObservable = new BABYLON.Observable();
  31346. }
  31347. return this._onAfterRenderObservable;
  31348. },
  31349. enumerable: true,
  31350. configurable: true
  31351. });
  31352. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31353. /**
  31354. * An event triggered before drawing the mesh
  31355. */
  31356. get: function () {
  31357. if (!this._onBeforeDrawObservable) {
  31358. this._onBeforeDrawObservable = new BABYLON.Observable();
  31359. }
  31360. return this._onBeforeDrawObservable;
  31361. },
  31362. enumerable: true,
  31363. configurable: true
  31364. });
  31365. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31366. set: function (callback) {
  31367. if (this._onBeforeDrawObserver) {
  31368. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31369. }
  31370. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31371. },
  31372. enumerable: true,
  31373. configurable: true
  31374. });
  31375. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31376. get: function () {
  31377. return this._morphTargetManager;
  31378. },
  31379. set: function (value) {
  31380. if (this._morphTargetManager === value) {
  31381. return;
  31382. }
  31383. this._morphTargetManager = value;
  31384. this._syncGeometryWithMorphTargetManager();
  31385. },
  31386. enumerable: true,
  31387. configurable: true
  31388. });
  31389. Object.defineProperty(Mesh.prototype, "source", {
  31390. get: function () {
  31391. return this._source;
  31392. },
  31393. enumerable: true,
  31394. configurable: true
  31395. });
  31396. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31397. get: function () {
  31398. return this._unIndexed;
  31399. },
  31400. set: function (value) {
  31401. if (this._unIndexed !== value) {
  31402. this._unIndexed = value;
  31403. this._markSubMeshesAsAttributesDirty();
  31404. }
  31405. },
  31406. enumerable: true,
  31407. configurable: true
  31408. });
  31409. // Methods
  31410. /**
  31411. * Returns the string "Mesh".
  31412. */
  31413. Mesh.prototype.getClassName = function () {
  31414. return "Mesh";
  31415. };
  31416. /**
  31417. * Returns a string.
  31418. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31419. */
  31420. Mesh.prototype.toString = function (fullDetails) {
  31421. var ret = _super.prototype.toString.call(this, fullDetails);
  31422. ret += ", n vertices: " + this.getTotalVertices();
  31423. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31424. if (this.animations) {
  31425. for (var i = 0; i < this.animations.length; i++) {
  31426. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31427. }
  31428. }
  31429. if (fullDetails) {
  31430. if (this._geometry) {
  31431. var ib = this.getIndices();
  31432. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31433. if (vb && ib) {
  31434. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31435. }
  31436. }
  31437. else {
  31438. ret += ", flat shading: UNKNOWN";
  31439. }
  31440. }
  31441. return ret;
  31442. };
  31443. /** @hidden */
  31444. Mesh.prototype._unBindEffect = function () {
  31445. _super.prototype._unBindEffect.call(this);
  31446. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31447. var instance = _a[_i];
  31448. instance._unBindEffect();
  31449. }
  31450. };
  31451. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31452. /**
  31453. * True if the mesh has some Levels Of Details (LOD).
  31454. * Returns a boolean.
  31455. */
  31456. get: function () {
  31457. return this._LODLevels.length > 0;
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. /**
  31463. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31464. * @returns an array of {BABYLON.MeshLODLevel}
  31465. */
  31466. Mesh.prototype.getLODLevels = function () {
  31467. return this._LODLevels;
  31468. };
  31469. Mesh.prototype._sortLODLevels = function () {
  31470. this._LODLevels.sort(function (a, b) {
  31471. if (a.distance < b.distance) {
  31472. return 1;
  31473. }
  31474. if (a.distance > b.distance) {
  31475. return -1;
  31476. }
  31477. return 0;
  31478. });
  31479. };
  31480. /**
  31481. * Add a mesh as LOD level triggered at the given distance.
  31482. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31483. * @param distance The distance from the center of the object to show this level
  31484. * @param mesh The mesh to be added as LOD level (can be null)
  31485. * @return This mesh (for chaining)
  31486. */
  31487. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31488. if (mesh && mesh._masterMesh) {
  31489. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31490. return this;
  31491. }
  31492. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31493. this._LODLevels.push(level);
  31494. if (mesh) {
  31495. mesh._masterMesh = this;
  31496. }
  31497. this._sortLODLevels();
  31498. return this;
  31499. };
  31500. /**
  31501. * Returns the LOD level mesh at the passed distance or null if not found.
  31502. * It is related to the method `addLODLevel(distance, mesh)`.
  31503. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31504. * Returns an object Mesh or `null`.
  31505. */
  31506. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31507. for (var index = 0; index < this._LODLevels.length; index++) {
  31508. var level = this._LODLevels[index];
  31509. if (level.distance === distance) {
  31510. return level.mesh;
  31511. }
  31512. }
  31513. return null;
  31514. };
  31515. /**
  31516. * Remove a mesh from the LOD array
  31517. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31518. * @param {Mesh} mesh The mesh to be removed.
  31519. * @return {Mesh} This mesh (for chaining)
  31520. */
  31521. Mesh.prototype.removeLODLevel = function (mesh) {
  31522. for (var index = 0; index < this._LODLevels.length; index++) {
  31523. if (this._LODLevels[index].mesh === mesh) {
  31524. this._LODLevels.splice(index, 1);
  31525. if (mesh) {
  31526. mesh._masterMesh = null;
  31527. }
  31528. }
  31529. }
  31530. this._sortLODLevels();
  31531. return this;
  31532. };
  31533. /**
  31534. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31535. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31536. */
  31537. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31538. if (!this._LODLevels || this._LODLevels.length === 0) {
  31539. return this;
  31540. }
  31541. var bSphere;
  31542. if (boundingSphere) {
  31543. bSphere = boundingSphere;
  31544. }
  31545. else {
  31546. var boundingInfo = this.getBoundingInfo();
  31547. bSphere = boundingInfo.boundingSphere;
  31548. }
  31549. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31550. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31551. if (this.onLODLevelSelection) {
  31552. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31553. }
  31554. return this;
  31555. }
  31556. for (var index = 0; index < this._LODLevels.length; index++) {
  31557. var level = this._LODLevels[index];
  31558. if (level.distance < distanceToCamera) {
  31559. if (level.mesh) {
  31560. level.mesh._preActivate();
  31561. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31562. }
  31563. if (this.onLODLevelSelection) {
  31564. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31565. }
  31566. return level.mesh;
  31567. }
  31568. }
  31569. if (this.onLODLevelSelection) {
  31570. this.onLODLevelSelection(distanceToCamera, this, this);
  31571. }
  31572. return this;
  31573. };
  31574. Object.defineProperty(Mesh.prototype, "geometry", {
  31575. /**
  31576. * Returns the mesh internal Geometry object.
  31577. */
  31578. get: function () {
  31579. return this._geometry;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. /**
  31585. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31586. */
  31587. Mesh.prototype.getTotalVertices = function () {
  31588. if (this._geometry === null || this._geometry === undefined) {
  31589. return 0;
  31590. }
  31591. return this._geometry.getTotalVertices();
  31592. };
  31593. /**
  31594. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31595. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31596. * You can force the copy with forceCopy === true
  31597. * Returns null if the mesh has no geometry or no vertex buffer.
  31598. * Possible `kind` values :
  31599. * - BABYLON.VertexBuffer.PositionKind
  31600. * - BABYLON.VertexBuffer.UVKind
  31601. * - BABYLON.VertexBuffer.UV2Kind
  31602. * - BABYLON.VertexBuffer.UV3Kind
  31603. * - BABYLON.VertexBuffer.UV4Kind
  31604. * - BABYLON.VertexBuffer.UV5Kind
  31605. * - BABYLON.VertexBuffer.UV6Kind
  31606. * - BABYLON.VertexBuffer.ColorKind
  31607. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31608. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31609. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31610. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31611. */
  31612. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31613. if (!this._geometry) {
  31614. return null;
  31615. }
  31616. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31617. };
  31618. /**
  31619. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31620. * Returns `null` if the mesh has no geometry.
  31621. * Possible `kind` values :
  31622. * - BABYLON.VertexBuffer.PositionKind
  31623. * - BABYLON.VertexBuffer.UVKind
  31624. * - BABYLON.VertexBuffer.UV2Kind
  31625. * - BABYLON.VertexBuffer.UV3Kind
  31626. * - BABYLON.VertexBuffer.UV4Kind
  31627. * - BABYLON.VertexBuffer.UV5Kind
  31628. * - BABYLON.VertexBuffer.UV6Kind
  31629. * - BABYLON.VertexBuffer.ColorKind
  31630. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31631. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31632. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31633. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31634. */
  31635. Mesh.prototype.getVertexBuffer = function (kind) {
  31636. if (!this._geometry) {
  31637. return null;
  31638. }
  31639. return this._geometry.getVertexBuffer(kind);
  31640. };
  31641. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31642. if (!this._geometry) {
  31643. if (this._delayInfo) {
  31644. return this._delayInfo.indexOf(kind) !== -1;
  31645. }
  31646. return false;
  31647. }
  31648. return this._geometry.isVerticesDataPresent(kind);
  31649. };
  31650. /**
  31651. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31652. * Possible `kind` values :
  31653. * - BABYLON.VertexBuffer.PositionKind
  31654. * - BABYLON.VertexBuffer.UVKind
  31655. * - BABYLON.VertexBuffer.UV2Kind
  31656. * - BABYLON.VertexBuffer.UV3Kind
  31657. * - BABYLON.VertexBuffer.UV4Kind
  31658. * - BABYLON.VertexBuffer.UV5Kind
  31659. * - BABYLON.VertexBuffer.UV6Kind
  31660. * - BABYLON.VertexBuffer.ColorKind
  31661. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31662. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31663. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31664. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31665. */
  31666. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31667. if (!this._geometry) {
  31668. if (this._delayInfo) {
  31669. return this._delayInfo.indexOf(kind) !== -1;
  31670. }
  31671. return false;
  31672. }
  31673. return this._geometry.isVertexBufferUpdatable(kind);
  31674. };
  31675. /**
  31676. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31677. * Possible `kind` values :
  31678. * - BABYLON.VertexBuffer.PositionKind
  31679. * - BABYLON.VertexBuffer.UVKind
  31680. * - BABYLON.VertexBuffer.UV2Kind
  31681. * - BABYLON.VertexBuffer.UV3Kind
  31682. * - BABYLON.VertexBuffer.UV4Kind
  31683. * - BABYLON.VertexBuffer.UV5Kind
  31684. * - BABYLON.VertexBuffer.UV6Kind
  31685. * - BABYLON.VertexBuffer.ColorKind
  31686. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31687. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31688. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31689. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31690. */
  31691. Mesh.prototype.getVerticesDataKinds = function () {
  31692. if (!this._geometry) {
  31693. var result = new Array();
  31694. if (this._delayInfo) {
  31695. this._delayInfo.forEach(function (kind, index, array) {
  31696. result.push(kind);
  31697. });
  31698. }
  31699. return result;
  31700. }
  31701. return this._geometry.getVerticesDataKinds();
  31702. };
  31703. /**
  31704. * Returns a positive integer : the total number of indices in this mesh geometry.
  31705. * Returns zero if the mesh has no geometry.
  31706. */
  31707. Mesh.prototype.getTotalIndices = function () {
  31708. if (!this._geometry) {
  31709. return 0;
  31710. }
  31711. return this._geometry.getTotalIndices();
  31712. };
  31713. /**
  31714. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31715. * @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.
  31716. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31717. * @returns the indices array or an empty array if the mesh has no geometry
  31718. */
  31719. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31720. if (!this._geometry) {
  31721. return [];
  31722. }
  31723. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31724. };
  31725. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31726. get: function () {
  31727. return this._masterMesh !== null && this._masterMesh !== undefined;
  31728. },
  31729. enumerable: true,
  31730. configurable: true
  31731. });
  31732. /**
  31733. * Determine if the current mesh is ready to be rendered
  31734. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31735. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31736. * @returns true if all associated assets are ready (material, textures, shaders)
  31737. */
  31738. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31739. if (completeCheck === void 0) { completeCheck = false; }
  31740. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31741. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31742. return false;
  31743. }
  31744. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31745. return false;
  31746. }
  31747. if (!this.subMeshes || this.subMeshes.length === 0) {
  31748. return true;
  31749. }
  31750. if (!completeCheck) {
  31751. return true;
  31752. }
  31753. var engine = this.getEngine();
  31754. var scene = this.getScene();
  31755. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31756. this.computeWorldMatrix();
  31757. var mat = this.material || scene.defaultMaterial;
  31758. if (mat) {
  31759. if (mat.storeEffectOnSubMeshes) {
  31760. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31761. var subMesh = _a[_i];
  31762. var effectiveMaterial = subMesh.getMaterial();
  31763. if (effectiveMaterial) {
  31764. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31765. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31766. return false;
  31767. }
  31768. }
  31769. else {
  31770. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31771. return false;
  31772. }
  31773. }
  31774. }
  31775. }
  31776. }
  31777. else {
  31778. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31779. return false;
  31780. }
  31781. }
  31782. }
  31783. // Shadows
  31784. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31785. var light = _c[_b];
  31786. var generator = light.getShadowGenerator();
  31787. if (generator) {
  31788. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31789. var subMesh = _e[_d];
  31790. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31791. return false;
  31792. }
  31793. }
  31794. }
  31795. }
  31796. // LOD
  31797. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31798. var lod = _g[_f];
  31799. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31800. return false;
  31801. }
  31802. }
  31803. return true;
  31804. };
  31805. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31806. /**
  31807. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31808. * This property is pertinent only for updatable parametric shapes.
  31809. */
  31810. get: function () {
  31811. return this._areNormalsFrozen;
  31812. },
  31813. enumerable: true,
  31814. configurable: true
  31815. });
  31816. /**
  31817. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31818. * It has no effect at all on other shapes.
  31819. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31820. * Returns the Mesh.
  31821. */
  31822. Mesh.prototype.freezeNormals = function () {
  31823. this._areNormalsFrozen = true;
  31824. return this;
  31825. };
  31826. /**
  31827. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31828. * It has no effect at all on other shapes.
  31829. * It reactivates the mesh normals computation if it was previously frozen.
  31830. * Returns the Mesh.
  31831. */
  31832. Mesh.prototype.unfreezeNormals = function () {
  31833. this._areNormalsFrozen = false;
  31834. return this;
  31835. };
  31836. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31837. /**
  31838. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31839. */
  31840. set: function (count) {
  31841. this._overridenInstanceCount = count;
  31842. },
  31843. enumerable: true,
  31844. configurable: true
  31845. });
  31846. // Methods
  31847. /** @hidden */
  31848. Mesh.prototype._preActivate = function () {
  31849. var sceneRenderId = this.getScene().getRenderId();
  31850. if (this._preActivateId === sceneRenderId) {
  31851. return this;
  31852. }
  31853. this._preActivateId = sceneRenderId;
  31854. this._visibleInstances = null;
  31855. return this;
  31856. };
  31857. /** @hidden */
  31858. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31859. if (this._visibleInstances) {
  31860. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31861. }
  31862. return this;
  31863. };
  31864. /** @hidden */
  31865. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31866. if (!this._visibleInstances) {
  31867. this._visibleInstances = {};
  31868. this._visibleInstances.defaultRenderId = renderId;
  31869. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31870. }
  31871. if (!this._visibleInstances[renderId]) {
  31872. this._visibleInstances[renderId] = new Array();
  31873. }
  31874. this._visibleInstances[renderId].push(instance);
  31875. return this;
  31876. };
  31877. /**
  31878. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31879. * This means the mesh underlying bounding box and sphere are recomputed.
  31880. * Returns the Mesh.
  31881. */
  31882. Mesh.prototype.refreshBoundingInfo = function () {
  31883. return this._refreshBoundingInfo(false);
  31884. };
  31885. /** @hidden */
  31886. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31887. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31888. return this;
  31889. }
  31890. var data = this._getPositionData(applySkeleton);
  31891. if (data) {
  31892. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31893. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31894. }
  31895. if (this.subMeshes) {
  31896. for (var index = 0; index < this.subMeshes.length; index++) {
  31897. this.subMeshes[index].refreshBoundingInfo();
  31898. }
  31899. }
  31900. this._updateBoundingInfo();
  31901. return this;
  31902. };
  31903. Mesh.prototype._getPositionData = function (applySkeleton) {
  31904. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31905. if (data && applySkeleton && this.skeleton) {
  31906. data = BABYLON.Tools.Slice(data);
  31907. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31908. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31909. if (matricesWeightsData && matricesIndicesData) {
  31910. var needExtras = this.numBoneInfluencers > 4;
  31911. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31912. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31913. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31914. var tempVector = BABYLON.Tmp.Vector3[0];
  31915. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31916. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31917. var matWeightIdx = 0;
  31918. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31919. finalMatrix.reset();
  31920. var inf;
  31921. var weight;
  31922. for (inf = 0; inf < 4; inf++) {
  31923. weight = matricesWeightsData[matWeightIdx + inf];
  31924. if (weight > 0) {
  31925. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31926. finalMatrix.addToSelf(tempMatrix);
  31927. }
  31928. }
  31929. if (needExtras) {
  31930. for (inf = 0; inf < 4; inf++) {
  31931. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31932. if (weight > 0) {
  31933. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31934. finalMatrix.addToSelf(tempMatrix);
  31935. }
  31936. }
  31937. }
  31938. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31939. tempVector.toArray(data, index);
  31940. }
  31941. }
  31942. }
  31943. return data;
  31944. };
  31945. /** @hidden */
  31946. Mesh.prototype._createGlobalSubMesh = function (force) {
  31947. var totalVertices = this.getTotalVertices();
  31948. if (!totalVertices || !this.getIndices()) {
  31949. return null;
  31950. }
  31951. // Check if we need to recreate the submeshes
  31952. if (this.subMeshes && this.subMeshes.length > 0) {
  31953. var ib = this.getIndices();
  31954. if (!ib) {
  31955. return null;
  31956. }
  31957. var totalIndices = ib.length;
  31958. var needToRecreate = false;
  31959. if (force) {
  31960. needToRecreate = true;
  31961. }
  31962. else {
  31963. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31964. var submesh = _a[_i];
  31965. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31966. needToRecreate = true;
  31967. break;
  31968. }
  31969. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31970. needToRecreate = true;
  31971. break;
  31972. }
  31973. }
  31974. }
  31975. if (!needToRecreate) {
  31976. return this.subMeshes[0];
  31977. }
  31978. }
  31979. this.releaseSubMeshes();
  31980. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31981. };
  31982. Mesh.prototype.subdivide = function (count) {
  31983. if (count < 1) {
  31984. return;
  31985. }
  31986. var totalIndices = this.getTotalIndices();
  31987. var subdivisionSize = (totalIndices / count) | 0;
  31988. var offset = 0;
  31989. // Ensure that subdivisionSize is a multiple of 3
  31990. while (subdivisionSize % 3 !== 0) {
  31991. subdivisionSize++;
  31992. }
  31993. this.releaseSubMeshes();
  31994. for (var index = 0; index < count; index++) {
  31995. if (offset >= totalIndices) {
  31996. break;
  31997. }
  31998. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31999. offset += subdivisionSize;
  32000. }
  32001. this.synchronizeInstances();
  32002. };
  32003. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32004. if (updatable === void 0) { updatable = false; }
  32005. if (!this._geometry) {
  32006. var vertexData = new BABYLON.VertexData();
  32007. vertexData.set(data, kind);
  32008. var scene = this.getScene();
  32009. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32010. }
  32011. else {
  32012. this._geometry.setVerticesData(kind, data, updatable, stride);
  32013. }
  32014. return this;
  32015. };
  32016. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32017. if (updatable === void 0) { updatable = true; }
  32018. var vb = this.getVertexBuffer(kind);
  32019. if (!vb || vb.isUpdatable() === updatable) {
  32020. return;
  32021. }
  32022. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32023. };
  32024. /**
  32025. * Sets the mesh VertexBuffer.
  32026. * Returns the Mesh.
  32027. */
  32028. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32029. if (!this._geometry) {
  32030. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32031. }
  32032. this._geometry.setVerticesBuffer(buffer);
  32033. return this;
  32034. };
  32035. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32036. if (!this._geometry) {
  32037. return this;
  32038. }
  32039. if (!makeItUnique) {
  32040. this._geometry.updateVerticesData(kind, data, updateExtends);
  32041. }
  32042. else {
  32043. this.makeGeometryUnique();
  32044. this.updateVerticesData(kind, data, updateExtends, false);
  32045. }
  32046. return this;
  32047. };
  32048. /**
  32049. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32050. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32051. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32052. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32053. * Returns the Mesh.
  32054. */
  32055. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32056. if (computeNormals === void 0) { computeNormals = true; }
  32057. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32058. if (!positions) {
  32059. return this;
  32060. }
  32061. positionFunction(positions);
  32062. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32063. if (computeNormals) {
  32064. var indices = this.getIndices();
  32065. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32066. if (!normals) {
  32067. return this;
  32068. }
  32069. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32070. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32071. }
  32072. return this;
  32073. };
  32074. /**
  32075. * Creates a un-shared specific occurence of the geometry for the mesh.
  32076. * Returns the Mesh.
  32077. */
  32078. Mesh.prototype.makeGeometryUnique = function () {
  32079. if (!this._geometry) {
  32080. return this;
  32081. }
  32082. var oldGeometry = this._geometry;
  32083. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32084. oldGeometry.releaseForMesh(this, true);
  32085. geometry.applyToMesh(this);
  32086. return this;
  32087. };
  32088. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32089. if (totalVertices === void 0) { totalVertices = null; }
  32090. if (updatable === void 0) { updatable = false; }
  32091. if (!this._geometry) {
  32092. var vertexData = new BABYLON.VertexData();
  32093. vertexData.indices = indices;
  32094. var scene = this.getScene();
  32095. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32096. }
  32097. else {
  32098. this._geometry.setIndices(indices, totalVertices, updatable);
  32099. }
  32100. return this;
  32101. };
  32102. /**
  32103. * Update the current index buffer
  32104. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32105. * Returns the Mesh.
  32106. */
  32107. Mesh.prototype.updateIndices = function (indices, offset) {
  32108. if (!this._geometry) {
  32109. return this;
  32110. }
  32111. this._geometry.updateIndices(indices, offset);
  32112. return this;
  32113. };
  32114. /**
  32115. * Invert the geometry to move from a right handed system to a left handed one.
  32116. * Returns the Mesh.
  32117. */
  32118. Mesh.prototype.toLeftHanded = function () {
  32119. if (!this._geometry) {
  32120. return this;
  32121. }
  32122. this._geometry.toLeftHanded();
  32123. return this;
  32124. };
  32125. /** @hidden */
  32126. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32127. if (!this._geometry) {
  32128. return this;
  32129. }
  32130. var engine = this.getScene().getEngine();
  32131. // Wireframe
  32132. var indexToBind;
  32133. if (this._unIndexed) {
  32134. indexToBind = null;
  32135. }
  32136. else {
  32137. switch (fillMode) {
  32138. case BABYLON.Material.PointFillMode:
  32139. indexToBind = null;
  32140. break;
  32141. case BABYLON.Material.WireFrameFillMode:
  32142. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32143. break;
  32144. default:
  32145. case BABYLON.Material.TriangleFillMode:
  32146. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32147. break;
  32148. }
  32149. }
  32150. // VBOs
  32151. this._geometry._bind(effect, indexToBind);
  32152. return this;
  32153. };
  32154. /** @hidden */
  32155. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32156. if (alternate === void 0) { alternate = false; }
  32157. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32158. return this;
  32159. }
  32160. if (this._onBeforeDrawObservable) {
  32161. this._onBeforeDrawObservable.notifyObservers(this);
  32162. }
  32163. var scene = this.getScene();
  32164. var engine = scene.getEngine();
  32165. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32166. // or triangles as points
  32167. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32168. }
  32169. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32170. // Triangles as wireframe
  32171. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32172. }
  32173. else {
  32174. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32175. }
  32176. if (scene._isAlternateRenderingEnabled && !alternate) {
  32177. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32178. if (!effect || !scene.activeCamera) {
  32179. return this;
  32180. }
  32181. scene._switchToAlternateCameraConfiguration(true);
  32182. this._effectiveMaterial.bindView(effect);
  32183. this._effectiveMaterial.bindViewProjection(effect);
  32184. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32185. this._draw(subMesh, fillMode, instancesCount, true);
  32186. engine.setViewport(scene.activeCamera.viewport);
  32187. scene._switchToAlternateCameraConfiguration(false);
  32188. this._effectiveMaterial.bindView(effect);
  32189. this._effectiveMaterial.bindViewProjection(effect);
  32190. }
  32191. return this;
  32192. };
  32193. /**
  32194. * Registers for this mesh a javascript function called just before the rendering process.
  32195. * This function is passed the current mesh.
  32196. * Return the Mesh.
  32197. */
  32198. Mesh.prototype.registerBeforeRender = function (func) {
  32199. this.onBeforeRenderObservable.add(func);
  32200. return this;
  32201. };
  32202. /**
  32203. * Disposes a previously registered javascript function called before the rendering.
  32204. * This function is passed the current mesh.
  32205. * Returns the Mesh.
  32206. */
  32207. Mesh.prototype.unregisterBeforeRender = function (func) {
  32208. this.onBeforeRenderObservable.removeCallback(func);
  32209. return this;
  32210. };
  32211. /**
  32212. * Registers for this mesh a javascript function called just after the rendering is complete.
  32213. * This function is passed the current mesh.
  32214. * Returns the Mesh.
  32215. */
  32216. Mesh.prototype.registerAfterRender = function (func) {
  32217. this.onAfterRenderObservable.add(func);
  32218. return this;
  32219. };
  32220. /**
  32221. * Disposes a previously registered javascript function called after the rendering.
  32222. * This function is passed the current mesh.
  32223. * Return the Mesh.
  32224. */
  32225. Mesh.prototype.unregisterAfterRender = function (func) {
  32226. this.onAfterRenderObservable.removeCallback(func);
  32227. return this;
  32228. };
  32229. /** @hidden */
  32230. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32231. var scene = this.getScene();
  32232. this._batchCache.mustReturn = false;
  32233. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32234. this._batchCache.visibleInstances[subMeshId] = null;
  32235. if (this._visibleInstances) {
  32236. var currentRenderId = scene.getRenderId();
  32237. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32238. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32239. var selfRenderId = this._renderId;
  32240. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32241. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32242. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32243. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32244. }
  32245. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32246. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32247. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32248. this._batchCache.mustReturn = true;
  32249. return this._batchCache;
  32250. }
  32251. if (currentRenderId !== selfRenderId) {
  32252. this._batchCache.renderSelf[subMeshId] = false;
  32253. }
  32254. }
  32255. this._renderIdForInstances[subMeshId] = currentRenderId;
  32256. }
  32257. return this._batchCache;
  32258. };
  32259. /** @hidden */
  32260. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32261. var visibleInstances = batch.visibleInstances[subMesh._id];
  32262. if (!visibleInstances) {
  32263. return this;
  32264. }
  32265. var matricesCount = visibleInstances.length + 1;
  32266. var bufferSize = matricesCount * 16 * 4;
  32267. var currentInstancesBufferSize = this._instancesBufferSize;
  32268. var instancesBuffer = this._instancesBuffer;
  32269. while (this._instancesBufferSize < bufferSize) {
  32270. this._instancesBufferSize *= 2;
  32271. }
  32272. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32273. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32274. }
  32275. var offset = 0;
  32276. var instancesCount = 0;
  32277. var world = this.getWorldMatrix();
  32278. if (batch.renderSelf[subMesh._id]) {
  32279. world.copyToArray(this._instancesData, offset);
  32280. offset += 16;
  32281. instancesCount++;
  32282. }
  32283. if (visibleInstances) {
  32284. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32285. var instance = visibleInstances[instanceIndex];
  32286. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32287. offset += 16;
  32288. instancesCount++;
  32289. }
  32290. }
  32291. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32292. if (instancesBuffer) {
  32293. instancesBuffer.dispose();
  32294. }
  32295. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32296. this._instancesBuffer = instancesBuffer;
  32297. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32298. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32299. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32300. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32301. }
  32302. else {
  32303. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32304. }
  32305. this._bind(subMesh, effect, fillMode);
  32306. this._draw(subMesh, fillMode, instancesCount);
  32307. engine.unbindInstanceAttributes();
  32308. return this;
  32309. };
  32310. /** @hidden */
  32311. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32312. var scene = this.getScene();
  32313. var engine = scene.getEngine();
  32314. if (hardwareInstancedRendering) {
  32315. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32316. }
  32317. else {
  32318. if (batch.renderSelf[subMesh._id]) {
  32319. // Draw
  32320. if (onBeforeDraw) {
  32321. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32322. }
  32323. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32324. }
  32325. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32326. if (visibleInstancesForSubMesh) {
  32327. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32328. var instance = visibleInstancesForSubMesh[instanceIndex];
  32329. // World
  32330. var world = instance.getWorldMatrix();
  32331. if (onBeforeDraw) {
  32332. onBeforeDraw(true, world, effectiveMaterial);
  32333. }
  32334. // Draw
  32335. this._draw(subMesh, fillMode);
  32336. }
  32337. }
  32338. }
  32339. return this;
  32340. };
  32341. /**
  32342. * 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
  32343. * @param subMesh defines the subMesh to render
  32344. * @param enableAlphaMode defines if alpha mode can be changed
  32345. * @returns the current mesh
  32346. */
  32347. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32348. this._checkOcclusionQuery();
  32349. if (this._isOccluded) {
  32350. return this;
  32351. }
  32352. var scene = this.getScene();
  32353. // Managing instances
  32354. var batch = this._getInstancesRenderList(subMesh._id);
  32355. if (batch.mustReturn) {
  32356. return this;
  32357. }
  32358. // Checking geometry state
  32359. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32360. return this;
  32361. }
  32362. if (this._onBeforeRenderObservable) {
  32363. this._onBeforeRenderObservable.notifyObservers(this);
  32364. }
  32365. var engine = scene.getEngine();
  32366. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32367. // Material
  32368. var material = subMesh.getMaterial();
  32369. if (!material) {
  32370. return this;
  32371. }
  32372. this._effectiveMaterial = material;
  32373. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32374. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32375. return this;
  32376. }
  32377. }
  32378. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32379. return this;
  32380. }
  32381. // Alpha mode
  32382. if (enableAlphaMode) {
  32383. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32384. }
  32385. // Outline - step 1
  32386. var savedDepthWrite = engine.getDepthWrite();
  32387. if (this.renderOutline) {
  32388. engine.setDepthWrite(false);
  32389. scene.getOutlineRenderer().render(subMesh, batch);
  32390. engine.setDepthWrite(savedDepthWrite);
  32391. }
  32392. var effect;
  32393. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32394. effect = subMesh.effect;
  32395. }
  32396. else {
  32397. effect = this._effectiveMaterial.getEffect();
  32398. }
  32399. if (!effect) {
  32400. return this;
  32401. }
  32402. var sideOrientation = this.overrideMaterialSideOrientation;
  32403. if (sideOrientation == null) {
  32404. sideOrientation = this._effectiveMaterial.sideOrientation;
  32405. if (this._getWorldMatrixDeterminant() < 0) {
  32406. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32407. }
  32408. }
  32409. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32410. if (this._effectiveMaterial.forceDepthWrite) {
  32411. engine.setDepthWrite(true);
  32412. }
  32413. // Bind
  32414. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32415. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32416. this._bind(subMesh, effect, fillMode);
  32417. }
  32418. var world = this.getWorldMatrix();
  32419. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32420. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32421. }
  32422. else {
  32423. this._effectiveMaterial.bind(world, this);
  32424. }
  32425. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32426. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32427. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32428. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32429. }
  32430. // Draw
  32431. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32432. // Unbind
  32433. this._effectiveMaterial.unbind();
  32434. // Outline - step 2
  32435. if (this.renderOutline && savedDepthWrite) {
  32436. engine.setDepthWrite(true);
  32437. engine.setColorWrite(false);
  32438. scene.getOutlineRenderer().render(subMesh, batch);
  32439. engine.setColorWrite(true);
  32440. }
  32441. // Overlay
  32442. if (this.renderOverlay) {
  32443. var currentMode = engine.getAlphaMode();
  32444. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32445. scene.getOutlineRenderer().render(subMesh, batch, true);
  32446. engine.setAlphaMode(currentMode);
  32447. }
  32448. if (this._onAfterRenderObservable) {
  32449. this._onAfterRenderObservable.notifyObservers(this);
  32450. }
  32451. return this;
  32452. };
  32453. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32454. if (isInstance && effectiveMaterial) {
  32455. effectiveMaterial.bindOnlyWorldMatrix(world);
  32456. }
  32457. };
  32458. /**
  32459. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32460. */
  32461. Mesh.prototype.getEmittedParticleSystems = function () {
  32462. var results = new Array();
  32463. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32464. var particleSystem = this.getScene().particleSystems[index];
  32465. if (particleSystem.emitter === this) {
  32466. results.push(particleSystem);
  32467. }
  32468. }
  32469. return results;
  32470. };
  32471. /**
  32472. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32473. */
  32474. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32475. var results = new Array();
  32476. var descendants = this.getDescendants();
  32477. descendants.push(this);
  32478. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32479. var particleSystem = this.getScene().particleSystems[index];
  32480. var emitter = particleSystem.emitter;
  32481. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32482. results.push(particleSystem);
  32483. }
  32484. }
  32485. return results;
  32486. };
  32487. /**
  32488. * Normalize matrix weights so that all vertices have a total weight set to 1
  32489. */
  32490. Mesh.prototype.cleanMatrixWeights = function () {
  32491. var epsilon = 1e-3;
  32492. var noInfluenceBoneIndex = 0.0;
  32493. if (this.skeleton) {
  32494. noInfluenceBoneIndex = this.skeleton.bones.length;
  32495. }
  32496. else {
  32497. return;
  32498. }
  32499. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32500. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32501. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32502. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32503. var influencers = this.numBoneInfluencers;
  32504. var size = matricesWeights.length;
  32505. for (var i = 0; i < size; i += 4) {
  32506. var weight = 0.0;
  32507. var firstZeroWeight = -1;
  32508. for (var j = 0; j < 4; j++) {
  32509. var w = matricesWeights[i + j];
  32510. weight += w;
  32511. if (w < epsilon && firstZeroWeight < 0) {
  32512. firstZeroWeight = j;
  32513. }
  32514. }
  32515. if (matricesWeightsExtra) {
  32516. for (var j = 0; j < 4; j++) {
  32517. var w = matricesWeightsExtra[i + j];
  32518. weight += w;
  32519. if (w < epsilon && firstZeroWeight < 0) {
  32520. firstZeroWeight = j + 4;
  32521. }
  32522. }
  32523. }
  32524. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32525. firstZeroWeight = influencers - 1;
  32526. }
  32527. if (weight > epsilon) {
  32528. var mweight = 1.0 / weight;
  32529. for (var j = 0; j < 4; j++) {
  32530. matricesWeights[i + j] *= mweight;
  32531. }
  32532. if (matricesWeightsExtra) {
  32533. for (var j = 0; j < 4; j++) {
  32534. matricesWeightsExtra[i + j] *= mweight;
  32535. }
  32536. }
  32537. }
  32538. else {
  32539. if (firstZeroWeight >= 4) {
  32540. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32541. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32542. }
  32543. else {
  32544. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32545. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32546. }
  32547. }
  32548. }
  32549. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32550. if (matricesIndicesExtra) {
  32551. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32552. }
  32553. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32554. if (matricesWeightsExtra) {
  32555. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32556. }
  32557. };
  32558. /** @hidden */
  32559. Mesh.prototype._checkDelayState = function () {
  32560. var scene = this.getScene();
  32561. if (this._geometry) {
  32562. this._geometry.load(scene);
  32563. }
  32564. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32565. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32566. this._queueLoad(scene);
  32567. }
  32568. return this;
  32569. };
  32570. Mesh.prototype._queueLoad = function (scene) {
  32571. var _this = this;
  32572. scene._addPendingData(this);
  32573. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32574. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32575. if (data instanceof ArrayBuffer) {
  32576. _this._delayLoadingFunction(data, _this);
  32577. }
  32578. else {
  32579. _this._delayLoadingFunction(JSON.parse(data), _this);
  32580. }
  32581. _this.instances.forEach(function (instance) {
  32582. instance._syncSubMeshes();
  32583. });
  32584. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32585. scene._removePendingData(_this);
  32586. }, function () { }, scene.database, getBinaryData);
  32587. return this;
  32588. };
  32589. /**
  32590. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32591. * A mesh is in the frustum if its bounding box intersects the frustum
  32592. * @param frustumPlanes defines the frustum to test
  32593. * @returns true if the mesh is in the frustum planes
  32594. */
  32595. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32596. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32597. return false;
  32598. }
  32599. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32600. return false;
  32601. }
  32602. this._checkDelayState();
  32603. return true;
  32604. };
  32605. /**
  32606. * Sets the mesh material by the material or multiMaterial `id` property.
  32607. * The material `id` is a string identifying the material or the multiMaterial.
  32608. * This method returns the Mesh.
  32609. */
  32610. Mesh.prototype.setMaterialByID = function (id) {
  32611. var materials = this.getScene().materials;
  32612. var index;
  32613. for (index = materials.length - 1; index > -1; index--) {
  32614. if (materials[index].id === id) {
  32615. this.material = materials[index];
  32616. return this;
  32617. }
  32618. }
  32619. // Multi
  32620. var multiMaterials = this.getScene().multiMaterials;
  32621. for (index = multiMaterials.length - 1; index > -1; index--) {
  32622. if (multiMaterials[index].id === id) {
  32623. this.material = multiMaterials[index];
  32624. return this;
  32625. }
  32626. }
  32627. return this;
  32628. };
  32629. /**
  32630. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32631. */
  32632. Mesh.prototype.getAnimatables = function () {
  32633. var results = new Array();
  32634. if (this.material) {
  32635. results.push(this.material);
  32636. }
  32637. if (this.skeleton) {
  32638. results.push(this.skeleton);
  32639. }
  32640. return results;
  32641. };
  32642. /**
  32643. * Modifies the mesh geometry according to the passed transformation matrix.
  32644. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32645. * The mesh normals are modified accordingly the same transformation.
  32646. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32647. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32648. * Returns the Mesh.
  32649. */
  32650. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32651. // Position
  32652. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32653. return this;
  32654. }
  32655. var submeshes = this.subMeshes.splice(0);
  32656. this._resetPointsArrayCache();
  32657. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32658. var temp = new Array();
  32659. var index;
  32660. for (index = 0; index < data.length; index += 3) {
  32661. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32662. }
  32663. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32664. // Normals
  32665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32666. return this;
  32667. }
  32668. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32669. temp = [];
  32670. for (index = 0; index < data.length; index += 3) {
  32671. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32672. }
  32673. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32674. // flip faces?
  32675. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32676. this.flipFaces();
  32677. }
  32678. // Restore submeshes
  32679. this.releaseSubMeshes();
  32680. this.subMeshes = submeshes;
  32681. return this;
  32682. };
  32683. /**
  32684. * Modifies the mesh geometry according to its own current World Matrix.
  32685. * The mesh World Matrix is then reset.
  32686. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32687. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32688. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32689. * Returns the Mesh.
  32690. */
  32691. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32692. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32693. this.scaling.copyFromFloats(1, 1, 1);
  32694. this.position.copyFromFloats(0, 0, 0);
  32695. this.rotation.copyFromFloats(0, 0, 0);
  32696. //only if quaternion is already set
  32697. if (this.rotationQuaternion) {
  32698. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32699. }
  32700. this._worldMatrix = BABYLON.Matrix.Identity();
  32701. return this;
  32702. };
  32703. Object.defineProperty(Mesh.prototype, "_positions", {
  32704. // Cache
  32705. get: function () {
  32706. if (this._geometry) {
  32707. return this._geometry._positions;
  32708. }
  32709. return null;
  32710. },
  32711. enumerable: true,
  32712. configurable: true
  32713. });
  32714. /** @hidden */
  32715. Mesh.prototype._resetPointsArrayCache = function () {
  32716. if (this._geometry) {
  32717. this._geometry._resetPointsArrayCache();
  32718. }
  32719. return this;
  32720. };
  32721. /** @hidden */
  32722. Mesh.prototype._generatePointsArray = function () {
  32723. if (this._geometry) {
  32724. return this._geometry._generatePointsArray();
  32725. }
  32726. return false;
  32727. };
  32728. /**
  32729. * Returns a new Mesh object generated from the current mesh properties.
  32730. * This method must not get confused with createInstance().
  32731. * The parameter `name` is a string, the name given to the new mesh.
  32732. * The optional parameter `newParent` can be any Node object (default `null`).
  32733. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32734. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32735. */
  32736. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32737. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32738. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32739. };
  32740. /**
  32741. * Releases resources associated with this mesh.
  32742. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32743. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32744. */
  32745. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32746. var _this = this;
  32747. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32748. this.morphTargetManager = null;
  32749. if (this._geometry) {
  32750. this._geometry.releaseForMesh(this, true);
  32751. }
  32752. if (this._onBeforeDrawObservable) {
  32753. this._onBeforeDrawObservable.clear();
  32754. }
  32755. if (this._onBeforeRenderObservable) {
  32756. this._onBeforeRenderObservable.clear();
  32757. }
  32758. if (this._onAfterRenderObservable) {
  32759. this._onAfterRenderObservable.clear();
  32760. }
  32761. // Sources
  32762. var meshes = this.getScene().meshes;
  32763. meshes.forEach(function (abstractMesh) {
  32764. var mesh = abstractMesh;
  32765. if (mesh._source && mesh._source === _this) {
  32766. mesh._source = null;
  32767. }
  32768. });
  32769. this._source = null;
  32770. // Instances
  32771. if (this._instancesBuffer) {
  32772. this._instancesBuffer.dispose();
  32773. this._instancesBuffer = null;
  32774. }
  32775. while (this.instances.length) {
  32776. this.instances[0].dispose();
  32777. }
  32778. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32779. };
  32780. /**
  32781. * Modifies the mesh geometry according to a displacement map.
  32782. * 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.
  32783. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32784. * This method returns nothing.
  32785. * @param url is a string, the URL from the image file is to be downloaded.
  32786. * @param minHeight is the lower limit of the displacement.
  32787. * @param maxHeight is the upper limit of the displacement.
  32788. * @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.
  32789. * @param uvOffset is an optional vector2 used to offset UV.
  32790. * @param uvScale is an optional vector2 used to scale UV.
  32791. * @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.
  32792. * @returns the Mesh.
  32793. */
  32794. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32795. var _this = this;
  32796. if (forceUpdate === void 0) { forceUpdate = false; }
  32797. var scene = this.getScene();
  32798. var onload = function (img) {
  32799. // Getting height map data
  32800. var canvas = document.createElement("canvas");
  32801. var context = canvas.getContext("2d");
  32802. var heightMapWidth = img.width;
  32803. var heightMapHeight = img.height;
  32804. canvas.width = heightMapWidth;
  32805. canvas.height = heightMapHeight;
  32806. context.drawImage(img, 0, 0);
  32807. // Create VertexData from map data
  32808. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32809. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32810. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32811. //execute success callback, if set
  32812. if (onSuccess) {
  32813. onSuccess(_this);
  32814. }
  32815. };
  32816. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32817. return this;
  32818. };
  32819. /**
  32820. * Modifies the mesh geometry according to a displacementMap buffer.
  32821. * 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.
  32822. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32823. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32824. * @param heightMapWidth is the width of the buffer image.
  32825. * @param heightMapHeight is the height of the buffer image.
  32826. * @param minHeight is the lower limit of the displacement.
  32827. * @param maxHeight is the upper limit of the displacement.
  32828. * @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.
  32829. * @param uvOffset is an optional vector2 used to offset UV.
  32830. * @param uvScale is an optional vector2 used to scale UV.
  32831. * @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.
  32832. * @returns the Mesh.
  32833. */
  32834. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32835. if (forceUpdate === void 0) { forceUpdate = false; }
  32836. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32837. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32838. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32839. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32840. return this;
  32841. }
  32842. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32843. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32844. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32845. var position = BABYLON.Vector3.Zero();
  32846. var normal = BABYLON.Vector3.Zero();
  32847. var uv = BABYLON.Vector2.Zero();
  32848. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32849. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32850. for (var index = 0; index < positions.length; index += 3) {
  32851. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32852. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32853. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32854. // Compute height
  32855. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32856. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32857. var pos = (u + v * heightMapWidth) * 4;
  32858. var r = buffer[pos] / 255.0;
  32859. var g = buffer[pos + 1] / 255.0;
  32860. var b = buffer[pos + 2] / 255.0;
  32861. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32862. normal.normalize();
  32863. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32864. position = position.add(normal);
  32865. position.toArray(positions, index);
  32866. }
  32867. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32868. if (forceUpdate) {
  32869. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32870. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32871. }
  32872. else {
  32873. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32874. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32875. }
  32876. return this;
  32877. };
  32878. /**
  32879. * Modify the mesh to get a flat shading rendering.
  32880. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32881. * This method returns the Mesh.
  32882. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32883. */
  32884. Mesh.prototype.convertToFlatShadedMesh = function () {
  32885. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32886. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32887. var kinds = this.getVerticesDataKinds();
  32888. var vbs = {};
  32889. var data = {};
  32890. var newdata = {};
  32891. var updatableNormals = false;
  32892. var kindIndex;
  32893. var kind;
  32894. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32895. kind = kinds[kindIndex];
  32896. var vertexBuffer = this.getVertexBuffer(kind);
  32897. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32898. updatableNormals = vertexBuffer.isUpdatable();
  32899. kinds.splice(kindIndex, 1);
  32900. kindIndex--;
  32901. continue;
  32902. }
  32903. vbs[kind] = vertexBuffer;
  32904. data[kind] = vbs[kind].getData();
  32905. newdata[kind] = [];
  32906. }
  32907. // Save previous submeshes
  32908. var previousSubmeshes = this.subMeshes.slice(0);
  32909. var indices = this.getIndices();
  32910. var totalIndices = this.getTotalIndices();
  32911. // Generating unique vertices per face
  32912. var index;
  32913. for (index = 0; index < totalIndices; index++) {
  32914. var vertexIndex = indices[index];
  32915. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32916. kind = kinds[kindIndex];
  32917. var stride = vbs[kind].getStrideSize();
  32918. for (var offset = 0; offset < stride; offset++) {
  32919. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32920. }
  32921. }
  32922. }
  32923. // Updating faces & normal
  32924. var normals = [];
  32925. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32926. for (index = 0; index < totalIndices; index += 3) {
  32927. indices[index] = index;
  32928. indices[index + 1] = index + 1;
  32929. indices[index + 2] = index + 2;
  32930. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32931. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32932. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32933. var p1p2 = p1.subtract(p2);
  32934. var p3p2 = p3.subtract(p2);
  32935. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32936. // Store same normals for every vertex
  32937. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32938. normals.push(normal.x);
  32939. normals.push(normal.y);
  32940. normals.push(normal.z);
  32941. }
  32942. }
  32943. this.setIndices(indices);
  32944. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32945. // Updating vertex buffers
  32946. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32947. kind = kinds[kindIndex];
  32948. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32949. }
  32950. // Updating submeshes
  32951. this.releaseSubMeshes();
  32952. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32953. var previousOne = previousSubmeshes[submeshIndex];
  32954. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32955. }
  32956. this.synchronizeInstances();
  32957. return this;
  32958. };
  32959. /**
  32960. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32961. * In other words, more vertices, no more indices and a single bigger VBO.
  32962. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32963. * Returns the Mesh.
  32964. */
  32965. Mesh.prototype.convertToUnIndexedMesh = function () {
  32966. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32967. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32968. var kinds = this.getVerticesDataKinds();
  32969. var vbs = {};
  32970. var data = {};
  32971. var newdata = {};
  32972. var kindIndex;
  32973. var kind;
  32974. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32975. kind = kinds[kindIndex];
  32976. var vertexBuffer = this.getVertexBuffer(kind);
  32977. vbs[kind] = vertexBuffer;
  32978. data[kind] = vbs[kind].getData();
  32979. newdata[kind] = [];
  32980. }
  32981. // Save previous submeshes
  32982. var previousSubmeshes = this.subMeshes.slice(0);
  32983. var indices = this.getIndices();
  32984. var totalIndices = this.getTotalIndices();
  32985. // Generating unique vertices per face
  32986. var index;
  32987. for (index = 0; index < totalIndices; index++) {
  32988. var vertexIndex = indices[index];
  32989. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32990. kind = kinds[kindIndex];
  32991. var stride = vbs[kind].getStrideSize();
  32992. for (var offset = 0; offset < stride; offset++) {
  32993. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32994. }
  32995. }
  32996. }
  32997. // Updating indices
  32998. for (index = 0; index < totalIndices; index += 3) {
  32999. indices[index] = index;
  33000. indices[index + 1] = index + 1;
  33001. indices[index + 2] = index + 2;
  33002. }
  33003. this.setIndices(indices);
  33004. // Updating vertex buffers
  33005. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33006. kind = kinds[kindIndex];
  33007. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33008. }
  33009. // Updating submeshes
  33010. this.releaseSubMeshes();
  33011. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33012. var previousOne = previousSubmeshes[submeshIndex];
  33013. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33014. }
  33015. this._unIndexed = true;
  33016. this.synchronizeInstances();
  33017. return this;
  33018. };
  33019. /**
  33020. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33021. * This method returns the Mesh.
  33022. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33023. */
  33024. Mesh.prototype.flipFaces = function (flipNormals) {
  33025. if (flipNormals === void 0) { flipNormals = false; }
  33026. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33027. var i;
  33028. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33029. for (i = 0; i < vertex_data.normals.length; i++) {
  33030. vertex_data.normals[i] *= -1;
  33031. }
  33032. }
  33033. if (vertex_data.indices) {
  33034. var temp;
  33035. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33036. // reassign indices
  33037. temp = vertex_data.indices[i + 1];
  33038. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33039. vertex_data.indices[i + 2] = temp;
  33040. }
  33041. }
  33042. vertex_data.applyToMesh(this);
  33043. return this;
  33044. };
  33045. // Instances
  33046. /**
  33047. * Creates a new InstancedMesh object from the mesh model.
  33048. * An instance shares the same properties and the same material than its model.
  33049. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33050. * Only these properties of each instance can then be set individually :
  33051. * - position
  33052. * - rotation
  33053. * - rotationQuaternion
  33054. * - setPivotMatrix
  33055. * - scaling
  33056. *
  33057. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33058. * Warning : this method is not supported for Line mesh and LineSystem
  33059. */
  33060. Mesh.prototype.createInstance = function (name) {
  33061. return new BABYLON.InstancedMesh(name, this);
  33062. };
  33063. /**
  33064. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33065. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33066. * This method returns the Mesh.
  33067. */
  33068. Mesh.prototype.synchronizeInstances = function () {
  33069. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33070. var instance = this.instances[instanceIndex];
  33071. instance._syncSubMeshes();
  33072. }
  33073. return this;
  33074. };
  33075. /**
  33076. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33077. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33078. * This should be used together with the simplification to avoid disappearing triangles.
  33079. * Returns the Mesh.
  33080. * @param successCallback an optional success callback to be called after the optimization finished.
  33081. */
  33082. Mesh.prototype.optimizeIndices = function (successCallback) {
  33083. var _this = this;
  33084. var indices = this.getIndices();
  33085. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33086. if (!positions || !indices) {
  33087. return this;
  33088. }
  33089. var vectorPositions = new Array();
  33090. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33091. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33092. }
  33093. var dupes = new Array();
  33094. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33095. var realPos = vectorPositions.length - 1 - iteration;
  33096. var testedPosition = vectorPositions[realPos];
  33097. for (var j = 0; j < realPos; ++j) {
  33098. var againstPosition = vectorPositions[j];
  33099. if (testedPosition.equals(againstPosition)) {
  33100. dupes[realPos] = j;
  33101. break;
  33102. }
  33103. }
  33104. }, function () {
  33105. for (var i = 0; i < indices.length; ++i) {
  33106. indices[i] = dupes[indices[i]] || indices[i];
  33107. }
  33108. //indices are now reordered
  33109. var originalSubMeshes = _this.subMeshes.slice(0);
  33110. _this.setIndices(indices);
  33111. _this.subMeshes = originalSubMeshes;
  33112. if (successCallback) {
  33113. successCallback(_this);
  33114. }
  33115. });
  33116. return this;
  33117. };
  33118. Mesh.prototype.serialize = function (serializationObject) {
  33119. serializationObject.name = this.name;
  33120. serializationObject.id = this.id;
  33121. serializationObject.type = this.getClassName();
  33122. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33123. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33124. }
  33125. serializationObject.position = this.position.asArray();
  33126. if (this.rotationQuaternion) {
  33127. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33128. }
  33129. else if (this.rotation) {
  33130. serializationObject.rotation = this.rotation.asArray();
  33131. }
  33132. serializationObject.scaling = this.scaling.asArray();
  33133. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33134. serializationObject.isEnabled = this.isEnabled(false);
  33135. serializationObject.isVisible = this.isVisible;
  33136. serializationObject.infiniteDistance = this.infiniteDistance;
  33137. serializationObject.pickable = this.isPickable;
  33138. serializationObject.receiveShadows = this.receiveShadows;
  33139. serializationObject.billboardMode = this.billboardMode;
  33140. serializationObject.visibility = this.visibility;
  33141. serializationObject.checkCollisions = this.checkCollisions;
  33142. serializationObject.isBlocker = this.isBlocker;
  33143. // Parent
  33144. if (this.parent) {
  33145. serializationObject.parentId = this.parent.id;
  33146. }
  33147. // Geometry
  33148. serializationObject.isUnIndexed = this.isUnIndexed;
  33149. var geometry = this._geometry;
  33150. if (geometry) {
  33151. var geometryId = geometry.id;
  33152. serializationObject.geometryId = geometryId;
  33153. // SubMeshes
  33154. serializationObject.subMeshes = [];
  33155. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33156. var subMesh = this.subMeshes[subIndex];
  33157. serializationObject.subMeshes.push({
  33158. materialIndex: subMesh.materialIndex,
  33159. verticesStart: subMesh.verticesStart,
  33160. verticesCount: subMesh.verticesCount,
  33161. indexStart: subMesh.indexStart,
  33162. indexCount: subMesh.indexCount
  33163. });
  33164. }
  33165. }
  33166. // Material
  33167. if (this.material) {
  33168. serializationObject.materialId = this.material.id;
  33169. }
  33170. else {
  33171. this.material = null;
  33172. }
  33173. // Morph targets
  33174. if (this.morphTargetManager) {
  33175. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33176. }
  33177. // Skeleton
  33178. if (this.skeleton) {
  33179. serializationObject.skeletonId = this.skeleton.id;
  33180. }
  33181. // Physics
  33182. //TODO implement correct serialization for physics impostors.
  33183. var impostor = this.getPhysicsImpostor();
  33184. if (impostor) {
  33185. serializationObject.physicsMass = impostor.getParam("mass");
  33186. serializationObject.physicsFriction = impostor.getParam("friction");
  33187. serializationObject.physicsRestitution = impostor.getParam("mass");
  33188. serializationObject.physicsImpostor = impostor.type;
  33189. }
  33190. // Metadata
  33191. if (this.metadata) {
  33192. serializationObject.metadata = this.metadata;
  33193. }
  33194. // Instances
  33195. serializationObject.instances = [];
  33196. for (var index = 0; index < this.instances.length; index++) {
  33197. var instance = this.instances[index];
  33198. var serializationInstance = {
  33199. name: instance.name,
  33200. id: instance.id,
  33201. position: instance.position.asArray(),
  33202. scaling: instance.scaling.asArray()
  33203. };
  33204. if (instance.rotationQuaternion) {
  33205. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33206. }
  33207. else if (instance.rotation) {
  33208. serializationInstance.rotation = instance.rotation.asArray();
  33209. }
  33210. serializationObject.instances.push(serializationInstance);
  33211. // Animations
  33212. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33213. serializationInstance.ranges = instance.serializeAnimationRanges();
  33214. }
  33215. //
  33216. // Animations
  33217. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33218. serializationObject.ranges = this.serializeAnimationRanges();
  33219. // Layer mask
  33220. serializationObject.layerMask = this.layerMask;
  33221. // Alpha
  33222. serializationObject.alphaIndex = this.alphaIndex;
  33223. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33224. // Overlay
  33225. serializationObject.overlayAlpha = this.overlayAlpha;
  33226. serializationObject.overlayColor = this.overlayColor.asArray();
  33227. serializationObject.renderOverlay = this.renderOverlay;
  33228. // Fog
  33229. serializationObject.applyFog = this.applyFog;
  33230. // Action Manager
  33231. if (this.actionManager) {
  33232. serializationObject.actions = this.actionManager.serialize(this.name);
  33233. }
  33234. };
  33235. /** @hidden */
  33236. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33237. if (!this.geometry) {
  33238. return;
  33239. }
  33240. this._markSubMeshesAsAttributesDirty();
  33241. var morphTargetManager = this._morphTargetManager;
  33242. if (morphTargetManager && morphTargetManager.vertexCount) {
  33243. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33244. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33245. this.morphTargetManager = null;
  33246. return;
  33247. }
  33248. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33249. var morphTarget = morphTargetManager.getActiveTarget(index);
  33250. var positions = morphTarget.getPositions();
  33251. if (!positions) {
  33252. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33253. return;
  33254. }
  33255. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33256. var normals = morphTarget.getNormals();
  33257. if (normals) {
  33258. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33259. }
  33260. var tangents = morphTarget.getTangents();
  33261. if (tangents) {
  33262. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33263. }
  33264. }
  33265. }
  33266. else {
  33267. var index = 0;
  33268. // Positions
  33269. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33270. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33271. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33272. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33273. }
  33274. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33275. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33276. }
  33277. index++;
  33278. }
  33279. }
  33280. };
  33281. // Statics
  33282. /**
  33283. * Returns a new Mesh object parsed from the source provided.
  33284. * The parameter `parsedMesh` is the source.
  33285. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33286. */
  33287. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33288. var mesh;
  33289. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33290. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33291. }
  33292. else {
  33293. mesh = new Mesh(parsedMesh.name, scene);
  33294. }
  33295. mesh.id = parsedMesh.id;
  33296. if (BABYLON.Tags) {
  33297. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33298. }
  33299. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33300. if (parsedMesh.metadata !== undefined) {
  33301. mesh.metadata = parsedMesh.metadata;
  33302. }
  33303. if (parsedMesh.rotationQuaternion) {
  33304. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33305. }
  33306. else if (parsedMesh.rotation) {
  33307. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33308. }
  33309. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33310. if (parsedMesh.localMatrix) {
  33311. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33312. }
  33313. else if (parsedMesh.pivotMatrix) {
  33314. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33315. }
  33316. mesh.setEnabled(parsedMesh.isEnabled);
  33317. mesh.isVisible = parsedMesh.isVisible;
  33318. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33319. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33320. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33321. if (parsedMesh.applyFog !== undefined) {
  33322. mesh.applyFog = parsedMesh.applyFog;
  33323. }
  33324. if (parsedMesh.pickable !== undefined) {
  33325. mesh.isPickable = parsedMesh.pickable;
  33326. }
  33327. if (parsedMesh.alphaIndex !== undefined) {
  33328. mesh.alphaIndex = parsedMesh.alphaIndex;
  33329. }
  33330. mesh.receiveShadows = parsedMesh.receiveShadows;
  33331. mesh.billboardMode = parsedMesh.billboardMode;
  33332. if (parsedMesh.visibility !== undefined) {
  33333. mesh.visibility = parsedMesh.visibility;
  33334. }
  33335. mesh.checkCollisions = parsedMesh.checkCollisions;
  33336. if (parsedMesh.isBlocker !== undefined) {
  33337. mesh.isBlocker = parsedMesh.isBlocker;
  33338. }
  33339. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33340. // freezeWorldMatrix
  33341. if (parsedMesh.freezeWorldMatrix) {
  33342. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33343. }
  33344. // Parent
  33345. if (parsedMesh.parentId) {
  33346. mesh._waitingParentId = parsedMesh.parentId;
  33347. }
  33348. // Actions
  33349. if (parsedMesh.actions !== undefined) {
  33350. mesh._waitingActions = parsedMesh.actions;
  33351. }
  33352. // Overlay
  33353. if (parsedMesh.overlayAlpha !== undefined) {
  33354. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33355. }
  33356. if (parsedMesh.overlayColor !== undefined) {
  33357. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33358. }
  33359. if (parsedMesh.renderOverlay !== undefined) {
  33360. mesh.renderOverlay = parsedMesh.renderOverlay;
  33361. }
  33362. // Geometry
  33363. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33364. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33365. if (parsedMesh.delayLoadingFile) {
  33366. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33367. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33368. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33369. if (parsedMesh._binaryInfo) {
  33370. mesh._binaryInfo = parsedMesh._binaryInfo;
  33371. }
  33372. mesh._delayInfo = [];
  33373. if (parsedMesh.hasUVs) {
  33374. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33375. }
  33376. if (parsedMesh.hasUVs2) {
  33377. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33378. }
  33379. if (parsedMesh.hasUVs3) {
  33380. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33381. }
  33382. if (parsedMesh.hasUVs4) {
  33383. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33384. }
  33385. if (parsedMesh.hasUVs5) {
  33386. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33387. }
  33388. if (parsedMesh.hasUVs6) {
  33389. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33390. }
  33391. if (parsedMesh.hasColors) {
  33392. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33393. }
  33394. if (parsedMesh.hasMatricesIndices) {
  33395. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33396. }
  33397. if (parsedMesh.hasMatricesWeights) {
  33398. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33399. }
  33400. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33401. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33402. mesh._checkDelayState();
  33403. }
  33404. }
  33405. else {
  33406. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33407. }
  33408. // Material
  33409. if (parsedMesh.materialId) {
  33410. mesh.setMaterialByID(parsedMesh.materialId);
  33411. }
  33412. else {
  33413. mesh.material = null;
  33414. }
  33415. // Morph targets
  33416. if (parsedMesh.morphTargetManagerId > -1) {
  33417. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33418. }
  33419. // Skeleton
  33420. if (parsedMesh.skeletonId > -1) {
  33421. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33422. if (parsedMesh.numBoneInfluencers) {
  33423. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33424. }
  33425. }
  33426. // Animations
  33427. if (parsedMesh.animations) {
  33428. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33429. var parsedAnimation = parsedMesh.animations[animationIndex];
  33430. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33431. }
  33432. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33433. }
  33434. if (parsedMesh.autoAnimate) {
  33435. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33436. }
  33437. // Layer Mask
  33438. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33439. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33440. }
  33441. else {
  33442. mesh.layerMask = 0x0FFFFFFF;
  33443. }
  33444. // Physics
  33445. if (parsedMesh.physicsImpostor) {
  33446. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33447. mass: parsedMesh.physicsMass,
  33448. friction: parsedMesh.physicsFriction,
  33449. restitution: parsedMesh.physicsRestitution
  33450. }, scene);
  33451. }
  33452. // Instances
  33453. if (parsedMesh.instances) {
  33454. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33455. var parsedInstance = parsedMesh.instances[index];
  33456. var instance = mesh.createInstance(parsedInstance.name);
  33457. if (parsedInstance.id) {
  33458. instance.id = parsedInstance.id;
  33459. }
  33460. if (BABYLON.Tags) {
  33461. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33462. }
  33463. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33464. if (parsedInstance.parentId) {
  33465. instance._waitingParentId = parsedInstance.parentId;
  33466. }
  33467. if (parsedInstance.rotationQuaternion) {
  33468. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33469. }
  33470. else if (parsedInstance.rotation) {
  33471. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33472. }
  33473. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33474. instance.checkCollisions = mesh.checkCollisions;
  33475. if (parsedMesh.animations) {
  33476. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33477. parsedAnimation = parsedMesh.animations[animationIndex];
  33478. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33479. }
  33480. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33481. if (parsedMesh.autoAnimate) {
  33482. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33483. }
  33484. }
  33485. }
  33486. }
  33487. return mesh;
  33488. };
  33489. /**
  33490. * Creates a ribbon mesh.
  33491. * Please consider using the same method from the MeshBuilder class instead.
  33492. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33493. *
  33494. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33495. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33496. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33497. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33498. * 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.
  33499. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33500. * 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
  33501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33502. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33504. */
  33505. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33506. if (closeArray === void 0) { closeArray = false; }
  33507. if (updatable === void 0) { updatable = false; }
  33508. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33509. pathArray: pathArray,
  33510. closeArray: closeArray,
  33511. closePath: closePath,
  33512. offset: offset,
  33513. updatable: updatable,
  33514. sideOrientation: sideOrientation,
  33515. instance: instance
  33516. }, scene);
  33517. };
  33518. /**
  33519. * Creates a plane polygonal mesh. By default, this is a disc.
  33520. * Please consider using the same method from the MeshBuilder class instead.
  33521. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33522. * 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.
  33523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33524. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33526. */
  33527. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33528. if (scene === void 0) { scene = null; }
  33529. var options = {
  33530. radius: radius,
  33531. tessellation: tessellation,
  33532. sideOrientation: sideOrientation,
  33533. updatable: updatable
  33534. };
  33535. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33536. };
  33537. /**
  33538. * Creates a box mesh.
  33539. * Please consider using the same method from the MeshBuilder class instead.
  33540. * The parameter `size` sets the size (float) of each box side (default 1).
  33541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33542. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33544. */
  33545. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33546. if (scene === void 0) { scene = null; }
  33547. var options = {
  33548. size: size,
  33549. sideOrientation: sideOrientation,
  33550. updatable: updatable
  33551. };
  33552. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33553. };
  33554. /**
  33555. * Creates a sphere mesh.
  33556. * Please consider using the same method from the MeshBuilder class instead.
  33557. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33558. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33560. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33562. */
  33563. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33564. var options = {
  33565. segments: segments,
  33566. diameterX: diameter,
  33567. diameterY: diameter,
  33568. diameterZ: diameter,
  33569. sideOrientation: sideOrientation,
  33570. updatable: updatable
  33571. };
  33572. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33573. };
  33574. /**
  33575. * Creates a cylinder or a cone mesh.
  33576. * Please consider using the same method from the MeshBuilder class instead.
  33577. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33578. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33579. * 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.
  33580. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33581. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33583. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33585. */
  33586. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33587. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33588. if (scene !== undefined) {
  33589. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33590. updatable = scene;
  33591. }
  33592. scene = subdivisions;
  33593. subdivisions = 1;
  33594. }
  33595. var options = {
  33596. height: height,
  33597. diameterTop: diameterTop,
  33598. diameterBottom: diameterBottom,
  33599. tessellation: tessellation,
  33600. subdivisions: subdivisions,
  33601. sideOrientation: sideOrientation,
  33602. updatable: updatable
  33603. };
  33604. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33605. };
  33606. // Torus (Code from SharpDX.org)
  33607. /**
  33608. * Creates a torus mesh.
  33609. * Please consider using the same method from the MeshBuilder class instead.
  33610. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33611. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33612. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33613. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33614. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33616. */
  33617. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33618. var options = {
  33619. diameter: diameter,
  33620. thickness: thickness,
  33621. tessellation: tessellation,
  33622. sideOrientation: sideOrientation,
  33623. updatable: updatable
  33624. };
  33625. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33626. };
  33627. /**
  33628. * Creates a torus knot mesh.
  33629. * Please consider using the same method from the MeshBuilder class instead.
  33630. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33631. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33632. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33633. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33635. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33637. */
  33638. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33639. var options = {
  33640. radius: radius,
  33641. tube: tube,
  33642. radialSegments: radialSegments,
  33643. tubularSegments: tubularSegments,
  33644. p: p,
  33645. q: q,
  33646. sideOrientation: sideOrientation,
  33647. updatable: updatable
  33648. };
  33649. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33650. };
  33651. /**
  33652. * Creates a line mesh.
  33653. * Please consider using the same method from the MeshBuilder class instead.
  33654. * 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.
  33655. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33656. * The parameter `points` is an array successive Vector3.
  33657. * 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
  33658. * When updating an instance, remember that only point positions can change, not the number of points.
  33659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33660. */
  33661. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33662. if (scene === void 0) { scene = null; }
  33663. if (updatable === void 0) { updatable = false; }
  33664. if (instance === void 0) { instance = null; }
  33665. var options = {
  33666. points: points,
  33667. updatable: updatable,
  33668. instance: instance
  33669. };
  33670. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33671. };
  33672. /**
  33673. * Creates a dashed line mesh.
  33674. * Please consider using the same method from the MeshBuilder class instead.
  33675. * 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.
  33676. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33677. * The parameter `points` is an array successive Vector3.
  33678. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33679. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33680. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33681. * 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
  33682. * When updating an instance, remember that only point positions can change, not the number of points.
  33683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33684. */
  33685. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33686. if (scene === void 0) { scene = null; }
  33687. var options = {
  33688. points: points,
  33689. dashSize: dashSize,
  33690. gapSize: gapSize,
  33691. dashNb: dashNb,
  33692. updatable: updatable,
  33693. instance: instance
  33694. };
  33695. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33696. };
  33697. /**
  33698. * Creates a polygon mesh.
  33699. * Please consider using the same method from the MeshBuilder class instead.
  33700. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33701. * 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.
  33702. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33704. * Remember you can only change the shape positions, not their number when updating a polygon.
  33705. */
  33706. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33707. var options = {
  33708. shape: shape,
  33709. holes: holes,
  33710. updatable: updatable,
  33711. sideOrientation: sideOrientation
  33712. };
  33713. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33714. };
  33715. /**
  33716. * Creates an extruded polygon mesh, with depth in the Y direction.
  33717. * Please consider using the same method from the MeshBuilder class instead.
  33718. */
  33719. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33720. var options = {
  33721. shape: shape,
  33722. holes: holes,
  33723. depth: depth,
  33724. updatable: updatable,
  33725. sideOrientation: sideOrientation
  33726. };
  33727. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33728. };
  33729. /**
  33730. * Creates an extruded shape mesh.
  33731. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33732. * Please consider using the same method from the MeshBuilder class instead.
  33733. *
  33734. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33735. * 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
  33736. * extruded along the Z axis.
  33737. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33738. * 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.
  33739. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33740. * 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
  33741. * 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
  33742. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33743. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33744. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33746. */
  33747. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33748. if (scene === void 0) { scene = null; }
  33749. var options = {
  33750. shape: shape,
  33751. path: path,
  33752. scale: scale,
  33753. rotation: rotation,
  33754. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33755. sideOrientation: sideOrientation,
  33756. instance: instance,
  33757. updatable: updatable
  33758. };
  33759. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33760. };
  33761. /**
  33762. * Creates an custom extruded shape mesh.
  33763. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33764. * Please consider using the same method from the MeshBuilder class instead.
  33765. *
  33766. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33767. * 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
  33768. * extruded along the Z axis.
  33769. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33770. * 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
  33771. * and the distance of this point from the begining of the path :
  33772. * ```javascript
  33773. * var rotationFunction = function(i, distance) {
  33774. * // do things
  33775. * return rotationValue; }
  33776. * ```
  33777. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33778. * 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
  33779. * and the distance of this point from the begining of the path :
  33780. * ```javascript
  33781. * var scaleFunction = function(i, distance) {
  33782. * // do things
  33783. * return scaleValue;}
  33784. * ```
  33785. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33786. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33787. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33788. * 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
  33789. * 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
  33790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33792. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33794. */
  33795. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33796. var options = {
  33797. shape: shape,
  33798. path: path,
  33799. scaleFunction: scaleFunction,
  33800. rotationFunction: rotationFunction,
  33801. ribbonCloseArray: ribbonCloseArray,
  33802. ribbonClosePath: ribbonClosePath,
  33803. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33804. sideOrientation: sideOrientation,
  33805. instance: instance,
  33806. updatable: updatable
  33807. };
  33808. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33809. };
  33810. /**
  33811. * Creates lathe mesh.
  33812. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33813. * Please consider using the same method from the MeshBuilder class instead.
  33814. * 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
  33815. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33816. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33817. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33819. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33821. */
  33822. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33823. var options = {
  33824. shape: shape,
  33825. radius: radius,
  33826. tessellation: tessellation,
  33827. sideOrientation: sideOrientation,
  33828. updatable: updatable
  33829. };
  33830. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33831. };
  33832. /**
  33833. * Creates a plane mesh.
  33834. * Please consider using the same method from the MeshBuilder class instead.
  33835. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33837. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33839. */
  33840. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33841. var options = {
  33842. size: size,
  33843. width: size,
  33844. height: size,
  33845. sideOrientation: sideOrientation,
  33846. updatable: updatable
  33847. };
  33848. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33849. };
  33850. /**
  33851. * Creates a ground mesh.
  33852. * Please consider using the same method from the MeshBuilder class instead.
  33853. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33854. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33855. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33856. */
  33857. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33858. var options = {
  33859. width: width,
  33860. height: height,
  33861. subdivisions: subdivisions,
  33862. updatable: updatable
  33863. };
  33864. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33865. };
  33866. /**
  33867. * Creates a tiled ground mesh.
  33868. * Please consider using the same method from the MeshBuilder class instead.
  33869. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33870. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33871. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33872. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33873. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33874. * numbers of subdivisions on the ground width and height of each tile.
  33875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33876. */
  33877. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33878. var options = {
  33879. xmin: xmin,
  33880. zmin: zmin,
  33881. xmax: xmax,
  33882. zmax: zmax,
  33883. subdivisions: subdivisions,
  33884. precision: precision,
  33885. updatable: updatable
  33886. };
  33887. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33888. };
  33889. /**
  33890. * Creates a ground mesh from a height map.
  33891. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33892. * Please consider using the same method from the MeshBuilder class instead.
  33893. * The parameter `url` sets the URL of the height map image resource.
  33894. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33895. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33896. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33897. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33898. * 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).
  33899. * This function is passed the newly built mesh :
  33900. * ```javascript
  33901. * function(mesh) { // do things
  33902. * return; }
  33903. * ```
  33904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33905. */
  33906. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33907. var options = {
  33908. width: width,
  33909. height: height,
  33910. subdivisions: subdivisions,
  33911. minHeight: minHeight,
  33912. maxHeight: maxHeight,
  33913. updatable: updatable,
  33914. onReady: onReady
  33915. };
  33916. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33917. };
  33918. /**
  33919. * Creates a tube mesh.
  33920. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33921. * Please consider using the same method from the MeshBuilder class instead.
  33922. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33923. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33924. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33925. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33926. * 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.
  33927. * It must return a radius value (positive float) :
  33928. * ```javascript
  33929. * var radiusFunction = function(i, distance) {
  33930. * // do things
  33931. * return radius; }
  33932. * ```
  33933. * 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
  33934. * 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
  33935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33936. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33938. */
  33939. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33940. var options = {
  33941. path: path,
  33942. radius: radius,
  33943. tessellation: tessellation,
  33944. radiusFunction: radiusFunction,
  33945. arc: 1,
  33946. cap: cap,
  33947. updatable: updatable,
  33948. sideOrientation: sideOrientation,
  33949. instance: instance
  33950. };
  33951. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33952. };
  33953. /**
  33954. * Creates a polyhedron mesh.
  33955. * Please consider using the same method from the MeshBuilder class instead.
  33956. * 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
  33957. * to choose the wanted type.
  33958. * The parameter `size` (positive float, default 1) sets the polygon size.
  33959. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33960. * 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`.
  33961. * 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
  33962. * 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)`).
  33963. * 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
  33964. * 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.
  33965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33966. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33968. */
  33969. Mesh.CreatePolyhedron = function (name, options, scene) {
  33970. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33971. };
  33972. /**
  33973. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33974. * Please consider using the same method from the MeshBuilder class instead.
  33975. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33976. * 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`).
  33977. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33978. * 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.
  33979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33980. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33982. */
  33983. Mesh.CreateIcoSphere = function (name, options, scene) {
  33984. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33985. };
  33986. /**
  33987. * Creates a decal mesh.
  33988. * Please consider using the same method from the MeshBuilder class instead.
  33989. * 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.
  33990. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33991. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33992. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33993. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33994. */
  33995. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33996. var options = {
  33997. position: position,
  33998. normal: normal,
  33999. size: size,
  34000. angle: angle
  34001. };
  34002. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34003. };
  34004. // Skeletons
  34005. /**
  34006. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34007. */
  34008. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34009. if (!this._sourcePositions) {
  34010. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34011. if (!source) {
  34012. return this._sourcePositions;
  34013. }
  34014. this._sourcePositions = new Float32Array(source);
  34015. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34016. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34017. }
  34018. }
  34019. return this._sourcePositions;
  34020. };
  34021. /**
  34022. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34023. */
  34024. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34025. if (!this._sourceNormals) {
  34026. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34027. if (!source) {
  34028. return this._sourceNormals;
  34029. }
  34030. this._sourceNormals = new Float32Array(source);
  34031. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34032. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34033. }
  34034. }
  34035. return this._sourceNormals;
  34036. };
  34037. /**
  34038. * Updates the vertex buffer by applying transformation from the bones.
  34039. * Returns the Mesh.
  34040. *
  34041. * @param {skeleton} skeleton to apply
  34042. */
  34043. Mesh.prototype.applySkeleton = function (skeleton) {
  34044. if (!this.geometry) {
  34045. return this;
  34046. }
  34047. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34048. return this;
  34049. }
  34050. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34051. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34052. return this;
  34053. }
  34054. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34055. return this;
  34056. }
  34057. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34058. return this;
  34059. }
  34060. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34061. return this;
  34062. }
  34063. if (!this._sourcePositions) {
  34064. var submeshes = this.subMeshes.slice();
  34065. this.setPositionsForCPUSkinning();
  34066. this.subMeshes = submeshes;
  34067. }
  34068. if (!this._sourceNormals) {
  34069. this.setNormalsForCPUSkinning();
  34070. }
  34071. // positionsData checks for not being Float32Array will only pass at most once
  34072. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34073. if (!positionsData) {
  34074. return this;
  34075. }
  34076. if (!(positionsData instanceof Float32Array)) {
  34077. positionsData = new Float32Array(positionsData);
  34078. }
  34079. // normalsData checks for not being Float32Array will only pass at most once
  34080. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34081. if (!normalsData) {
  34082. return this;
  34083. }
  34084. if (!(normalsData instanceof Float32Array)) {
  34085. normalsData = new Float32Array(normalsData);
  34086. }
  34087. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34088. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34089. if (!matricesWeightsData || !matricesIndicesData) {
  34090. return this;
  34091. }
  34092. var needExtras = this.numBoneInfluencers > 4;
  34093. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34094. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34095. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34096. var tempVector3 = BABYLON.Vector3.Zero();
  34097. var finalMatrix = new BABYLON.Matrix();
  34098. var tempMatrix = new BABYLON.Matrix();
  34099. var matWeightIdx = 0;
  34100. var inf;
  34101. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34102. var weight;
  34103. for (inf = 0; inf < 4; inf++) {
  34104. weight = matricesWeightsData[matWeightIdx + inf];
  34105. if (weight > 0) {
  34106. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34107. finalMatrix.addToSelf(tempMatrix);
  34108. }
  34109. }
  34110. if (needExtras) {
  34111. for (inf = 0; inf < 4; inf++) {
  34112. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34113. if (weight > 0) {
  34114. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34115. finalMatrix.addToSelf(tempMatrix);
  34116. }
  34117. }
  34118. }
  34119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34120. tempVector3.toArray(positionsData, index);
  34121. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34122. tempVector3.toArray(normalsData, index);
  34123. finalMatrix.reset();
  34124. }
  34125. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34126. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34127. return this;
  34128. };
  34129. // Tools
  34130. /**
  34131. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34132. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34133. */
  34134. Mesh.MinMax = function (meshes) {
  34135. var minVector = null;
  34136. var maxVector = null;
  34137. meshes.forEach(function (mesh, index, array) {
  34138. var boundingInfo = mesh.getBoundingInfo();
  34139. var boundingBox = boundingInfo.boundingBox;
  34140. if (!minVector || !maxVector) {
  34141. minVector = boundingBox.minimumWorld;
  34142. maxVector = boundingBox.maximumWorld;
  34143. }
  34144. else {
  34145. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34146. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34147. }
  34148. });
  34149. if (!minVector || !maxVector) {
  34150. return {
  34151. min: BABYLON.Vector3.Zero(),
  34152. max: BABYLON.Vector3.Zero()
  34153. };
  34154. }
  34155. return {
  34156. min: minVector,
  34157. max: maxVector
  34158. };
  34159. };
  34160. /**
  34161. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34162. */
  34163. Mesh.Center = function (meshesOrMinMaxVector) {
  34164. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34165. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34166. };
  34167. /**
  34168. * Merge the array of meshes into a single mesh for performance reasons.
  34169. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34170. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34171. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34172. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34173. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34174. */
  34175. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34176. if (disposeSource === void 0) { disposeSource = true; }
  34177. var index;
  34178. if (!allow32BitsIndices) {
  34179. var totalVertices = 0;
  34180. // Counting vertices
  34181. for (index = 0; index < meshes.length; index++) {
  34182. if (meshes[index]) {
  34183. totalVertices += meshes[index].getTotalVertices();
  34184. if (totalVertices > 65536) {
  34185. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34186. return null;
  34187. }
  34188. }
  34189. }
  34190. }
  34191. // Merge
  34192. var vertexData = null;
  34193. var otherVertexData;
  34194. var indiceArray = new Array();
  34195. var source = null;
  34196. for (index = 0; index < meshes.length; index++) {
  34197. if (meshes[index]) {
  34198. var wm = meshes[index].computeWorldMatrix(true);
  34199. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34200. otherVertexData.transform(wm);
  34201. if (vertexData) {
  34202. vertexData.merge(otherVertexData, allow32BitsIndices);
  34203. }
  34204. else {
  34205. vertexData = otherVertexData;
  34206. source = meshes[index];
  34207. }
  34208. if (subdivideWithSubMeshes) {
  34209. indiceArray.push(meshes[index].getTotalIndices());
  34210. }
  34211. }
  34212. }
  34213. source = source;
  34214. if (!meshSubclass) {
  34215. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34216. }
  34217. vertexData.applyToMesh(meshSubclass);
  34218. // Setting properties
  34219. meshSubclass.material = source.material;
  34220. meshSubclass.checkCollisions = source.checkCollisions;
  34221. // Cleaning
  34222. if (disposeSource) {
  34223. for (index = 0; index < meshes.length; index++) {
  34224. if (meshes[index]) {
  34225. meshes[index].dispose();
  34226. }
  34227. }
  34228. }
  34229. // Subdivide
  34230. if (subdivideWithSubMeshes) {
  34231. //-- removal of global submesh
  34232. meshSubclass.releaseSubMeshes();
  34233. index = 0;
  34234. var offset = 0;
  34235. //-- apply subdivision according to index table
  34236. while (index < indiceArray.length) {
  34237. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34238. offset += indiceArray[index];
  34239. index++;
  34240. }
  34241. }
  34242. return meshSubclass;
  34243. };
  34244. // Consts
  34245. Mesh._FRONTSIDE = 0;
  34246. Mesh._BACKSIDE = 1;
  34247. Mesh._DOUBLESIDE = 2;
  34248. Mesh._DEFAULTSIDE = 0;
  34249. Mesh._NO_CAP = 0;
  34250. Mesh._CAP_START = 1;
  34251. Mesh._CAP_END = 2;
  34252. Mesh._CAP_ALL = 3;
  34253. return Mesh;
  34254. }(BABYLON.AbstractMesh));
  34255. BABYLON.Mesh = Mesh;
  34256. })(BABYLON || (BABYLON = {}));
  34257. //# sourceMappingURL=babylon.mesh.js.map
  34258. var BABYLON;
  34259. (function (BABYLON) {
  34260. var BaseSubMesh = /** @class */ (function () {
  34261. function BaseSubMesh() {
  34262. }
  34263. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34264. get: function () {
  34265. return this._materialEffect;
  34266. },
  34267. enumerable: true,
  34268. configurable: true
  34269. });
  34270. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34271. if (defines === void 0) { defines = null; }
  34272. if (this._materialEffect === effect) {
  34273. if (!effect) {
  34274. this._materialDefines = null;
  34275. }
  34276. return;
  34277. }
  34278. this._materialDefines = defines;
  34279. this._materialEffect = effect;
  34280. };
  34281. return BaseSubMesh;
  34282. }());
  34283. BABYLON.BaseSubMesh = BaseSubMesh;
  34284. var SubMesh = /** @class */ (function (_super) {
  34285. __extends(SubMesh, _super);
  34286. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34287. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34288. var _this = _super.call(this) || this;
  34289. _this.materialIndex = materialIndex;
  34290. _this.verticesStart = verticesStart;
  34291. _this.verticesCount = verticesCount;
  34292. _this.indexStart = indexStart;
  34293. _this.indexCount = indexCount;
  34294. /** @hidden */
  34295. _this._renderId = 0;
  34296. _this._mesh = mesh;
  34297. _this._renderingMesh = renderingMesh || mesh;
  34298. mesh.subMeshes.push(_this);
  34299. _this._trianglePlanes = [];
  34300. _this._id = mesh.subMeshes.length - 1;
  34301. if (createBoundingBox) {
  34302. _this.refreshBoundingInfo();
  34303. mesh.computeWorldMatrix(true);
  34304. }
  34305. return _this;
  34306. }
  34307. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34308. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34309. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34310. };
  34311. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34312. get: function () {
  34313. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34314. },
  34315. enumerable: true,
  34316. configurable: true
  34317. });
  34318. /**
  34319. * Returns the submesh BoudingInfo object.
  34320. */
  34321. SubMesh.prototype.getBoundingInfo = function () {
  34322. if (this.IsGlobal) {
  34323. return this._mesh.getBoundingInfo();
  34324. }
  34325. return this._boundingInfo;
  34326. };
  34327. /**
  34328. * Sets the submesh BoundingInfo.
  34329. * Return the SubMesh.
  34330. */
  34331. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34332. this._boundingInfo = boundingInfo;
  34333. return this;
  34334. };
  34335. /**
  34336. * Returns the mesh of the current submesh.
  34337. */
  34338. SubMesh.prototype.getMesh = function () {
  34339. return this._mesh;
  34340. };
  34341. /**
  34342. * Returns the rendering mesh of the submesh.
  34343. */
  34344. SubMesh.prototype.getRenderingMesh = function () {
  34345. return this._renderingMesh;
  34346. };
  34347. /**
  34348. * Returns the submesh material.
  34349. */
  34350. SubMesh.prototype.getMaterial = function () {
  34351. var rootMaterial = this._renderingMesh.material;
  34352. if (rootMaterial === null || rootMaterial === undefined) {
  34353. return this._mesh.getScene().defaultMaterial;
  34354. }
  34355. else if (rootMaterial.getSubMaterial) {
  34356. var multiMaterial = rootMaterial;
  34357. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34358. if (this._currentMaterial !== effectiveMaterial) {
  34359. this._currentMaterial = effectiveMaterial;
  34360. this._materialDefines = null;
  34361. }
  34362. return effectiveMaterial;
  34363. }
  34364. return rootMaterial;
  34365. };
  34366. // Methods
  34367. /**
  34368. * Sets a new updated BoundingInfo object to the submesh.
  34369. * Returns the SubMesh.
  34370. */
  34371. SubMesh.prototype.refreshBoundingInfo = function () {
  34372. this._lastColliderWorldVertices = null;
  34373. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34374. return this;
  34375. }
  34376. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34377. if (!data) {
  34378. this._boundingInfo = this._mesh.getBoundingInfo();
  34379. return this;
  34380. }
  34381. var indices = this._renderingMesh.getIndices();
  34382. var extend;
  34383. //is this the only submesh?
  34384. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34385. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34386. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34387. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34388. }
  34389. else {
  34390. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34391. }
  34392. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34393. return this;
  34394. };
  34395. /** @hidden */
  34396. SubMesh.prototype._checkCollision = function (collider) {
  34397. var boundingInfo = this.getBoundingInfo();
  34398. return boundingInfo._checkCollision(collider);
  34399. };
  34400. /**
  34401. * Updates the submesh BoundingInfo.
  34402. * Returns the Submesh.
  34403. */
  34404. SubMesh.prototype.updateBoundingInfo = function (world) {
  34405. var boundingInfo = this.getBoundingInfo();
  34406. if (!boundingInfo) {
  34407. this.refreshBoundingInfo();
  34408. boundingInfo = this.getBoundingInfo();
  34409. }
  34410. boundingInfo.update(world);
  34411. return this;
  34412. };
  34413. /**
  34414. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34415. * Boolean returned.
  34416. */
  34417. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34418. var boundingInfo = this.getBoundingInfo();
  34419. if (!boundingInfo) {
  34420. return false;
  34421. }
  34422. return boundingInfo.isInFrustum(frustumPlanes);
  34423. };
  34424. /**
  34425. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34426. * Boolean returned.
  34427. */
  34428. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34429. var boundingInfo = this.getBoundingInfo();
  34430. if (!boundingInfo) {
  34431. return false;
  34432. }
  34433. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34434. };
  34435. /**
  34436. * Renders the submesh.
  34437. * Returns it.
  34438. */
  34439. SubMesh.prototype.render = function (enableAlphaMode) {
  34440. this._renderingMesh.render(this, enableAlphaMode);
  34441. return this;
  34442. };
  34443. /**
  34444. * Returns a new Index Buffer.
  34445. * Type returned : WebGLBuffer.
  34446. */
  34447. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34448. if (!this._linesIndexBuffer) {
  34449. var linesIndices = [];
  34450. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34451. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34452. }
  34453. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34454. this.linesIndexCount = linesIndices.length;
  34455. }
  34456. return this._linesIndexBuffer;
  34457. };
  34458. /**
  34459. * True is the passed Ray intersects the submesh bounding box.
  34460. * Boolean returned.
  34461. */
  34462. SubMesh.prototype.canIntersects = function (ray) {
  34463. var boundingInfo = this.getBoundingInfo();
  34464. if (!boundingInfo) {
  34465. return false;
  34466. }
  34467. return ray.intersectsBox(boundingInfo.boundingBox);
  34468. };
  34469. /**
  34470. * Returns an object IntersectionInfo.
  34471. */
  34472. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34473. var intersectInfo = null;
  34474. var material = this.getMaterial();
  34475. if (!material) {
  34476. return null;
  34477. }
  34478. switch (material.fillMode) {
  34479. case BABYLON.Material.PointListDrawMode:
  34480. case BABYLON.Material.LineListDrawMode:
  34481. case BABYLON.Material.LineLoopDrawMode:
  34482. case BABYLON.Material.LineStripDrawMode:
  34483. case BABYLON.Material.TriangleFanDrawMode:
  34484. case BABYLON.Material.TriangleStripDrawMode:
  34485. return null;
  34486. }
  34487. // LineMesh first as it's also a Mesh...
  34488. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34489. var lineMesh = this._mesh;
  34490. // Line test
  34491. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34492. var p0 = positions[indices[index]];
  34493. var p1 = positions[indices[index + 1]];
  34494. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34495. if (length < 0) {
  34496. continue;
  34497. }
  34498. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34499. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34500. if (fastCheck) {
  34501. break;
  34502. }
  34503. }
  34504. }
  34505. }
  34506. else {
  34507. // Triangles test
  34508. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34509. var p0 = positions[indices[index]];
  34510. var p1 = positions[indices[index + 1]];
  34511. var p2 = positions[indices[index + 2]];
  34512. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34513. if (currentIntersectInfo) {
  34514. if (currentIntersectInfo.distance < 0) {
  34515. continue;
  34516. }
  34517. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34518. intersectInfo = currentIntersectInfo;
  34519. intersectInfo.faceId = index / 3;
  34520. if (fastCheck) {
  34521. break;
  34522. }
  34523. }
  34524. }
  34525. }
  34526. }
  34527. return intersectInfo;
  34528. };
  34529. /** @hidden */
  34530. SubMesh.prototype._rebuild = function () {
  34531. if (this._linesIndexBuffer) {
  34532. this._linesIndexBuffer = null;
  34533. }
  34534. };
  34535. // Clone
  34536. /**
  34537. * Creates a new Submesh from the passed Mesh.
  34538. */
  34539. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34540. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34541. if (!this.IsGlobal) {
  34542. var boundingInfo = this.getBoundingInfo();
  34543. if (!boundingInfo) {
  34544. return result;
  34545. }
  34546. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34547. }
  34548. return result;
  34549. };
  34550. // Dispose
  34551. /**
  34552. * Disposes the Submesh.
  34553. * Returns nothing.
  34554. */
  34555. SubMesh.prototype.dispose = function () {
  34556. if (this._linesIndexBuffer) {
  34557. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34558. this._linesIndexBuffer = null;
  34559. }
  34560. // Remove from mesh
  34561. var index = this._mesh.subMeshes.indexOf(this);
  34562. this._mesh.subMeshes.splice(index, 1);
  34563. };
  34564. // Statics
  34565. /**
  34566. * Creates a new Submesh from the passed parameters :
  34567. * - materialIndex (integer) : the index of the main mesh material.
  34568. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34569. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34570. * - mesh (Mesh) : the main mesh to create the submesh from.
  34571. * - renderingMesh (optional Mesh) : rendering mesh.
  34572. */
  34573. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34574. var minVertexIndex = Number.MAX_VALUE;
  34575. var maxVertexIndex = -Number.MAX_VALUE;
  34576. renderingMesh = (renderingMesh || mesh);
  34577. var indices = renderingMesh.getIndices();
  34578. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34579. var vertexIndex = indices[index];
  34580. if (vertexIndex < minVertexIndex)
  34581. minVertexIndex = vertexIndex;
  34582. if (vertexIndex > maxVertexIndex)
  34583. maxVertexIndex = vertexIndex;
  34584. }
  34585. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34586. };
  34587. return SubMesh;
  34588. }(BaseSubMesh));
  34589. BABYLON.SubMesh = SubMesh;
  34590. })(BABYLON || (BABYLON = {}));
  34591. //# sourceMappingURL=babylon.subMesh.js.map
  34592. var __assign = (this && this.__assign) || function () {
  34593. __assign = Object.assign || function(t) {
  34594. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34595. s = arguments[i];
  34596. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34597. t[p] = s[p];
  34598. }
  34599. return t;
  34600. };
  34601. return __assign.apply(this, arguments);
  34602. };
  34603. var BABYLON;
  34604. (function (BABYLON) {
  34605. /**
  34606. * Manages the defines for the Material
  34607. */
  34608. var MaterialDefines = /** @class */ (function () {
  34609. function MaterialDefines() {
  34610. this._isDirty = true;
  34611. /** @hidden */
  34612. this._areLightsDirty = true;
  34613. /** @hidden */
  34614. this._areAttributesDirty = true;
  34615. /** @hidden */
  34616. this._areTexturesDirty = true;
  34617. /** @hidden */
  34618. this._areFresnelDirty = true;
  34619. /** @hidden */
  34620. this._areMiscDirty = true;
  34621. /** @hidden */
  34622. this._areImageProcessingDirty = true;
  34623. /** @hidden */
  34624. this._normals = false;
  34625. /** @hidden */
  34626. this._uvs = false;
  34627. /** @hidden */
  34628. this._needNormals = false;
  34629. /** @hidden */
  34630. this._needUVs = false;
  34631. }
  34632. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34633. /**
  34634. * Specifies if the material needs to be re-calculated
  34635. */
  34636. get: function () {
  34637. return this._isDirty;
  34638. },
  34639. enumerable: true,
  34640. configurable: true
  34641. });
  34642. /**
  34643. * Marks the material to indicate that it has been re-calculated
  34644. */
  34645. MaterialDefines.prototype.markAsProcessed = function () {
  34646. this._isDirty = false;
  34647. this._areAttributesDirty = false;
  34648. this._areTexturesDirty = false;
  34649. this._areFresnelDirty = false;
  34650. this._areLightsDirty = false;
  34651. this._areMiscDirty = false;
  34652. this._areImageProcessingDirty = false;
  34653. };
  34654. /**
  34655. * Marks the material to indicate that it needs to be re-calculated
  34656. */
  34657. MaterialDefines.prototype.markAsUnprocessed = function () {
  34658. this._isDirty = true;
  34659. };
  34660. /**
  34661. * Marks the material to indicate all of its defines need to be re-calculated
  34662. */
  34663. MaterialDefines.prototype.markAllAsDirty = function () {
  34664. this._areTexturesDirty = true;
  34665. this._areAttributesDirty = true;
  34666. this._areLightsDirty = true;
  34667. this._areFresnelDirty = true;
  34668. this._areMiscDirty = true;
  34669. this._areImageProcessingDirty = true;
  34670. this._isDirty = true;
  34671. };
  34672. /**
  34673. * Marks the material to indicate that image processing needs to be re-calculated
  34674. */
  34675. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34676. this._areImageProcessingDirty = true;
  34677. this._isDirty = true;
  34678. };
  34679. /**
  34680. * Marks the material to indicate the lights need to be re-calculated
  34681. */
  34682. MaterialDefines.prototype.markAsLightDirty = function () {
  34683. this._areLightsDirty = true;
  34684. this._isDirty = true;
  34685. };
  34686. /**
  34687. * Marks the attribute state as changed
  34688. */
  34689. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34690. this._areAttributesDirty = true;
  34691. this._isDirty = true;
  34692. };
  34693. /**
  34694. * Marks the texture state as changed
  34695. */
  34696. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34697. this._areTexturesDirty = true;
  34698. this._isDirty = true;
  34699. };
  34700. /**
  34701. * Marks the fresnel state as changed
  34702. */
  34703. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34704. this._areFresnelDirty = true;
  34705. this._isDirty = true;
  34706. };
  34707. /**
  34708. * Marks the misc state as changed
  34709. */
  34710. MaterialDefines.prototype.markAsMiscDirty = function () {
  34711. this._areMiscDirty = true;
  34712. this._isDirty = true;
  34713. };
  34714. /**
  34715. * Rebuilds the material defines
  34716. */
  34717. MaterialDefines.prototype.rebuild = function () {
  34718. if (this._keys) {
  34719. delete this._keys;
  34720. }
  34721. this._keys = [];
  34722. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34723. var key = _a[_i];
  34724. if (key[0] === "_") {
  34725. continue;
  34726. }
  34727. this._keys.push(key);
  34728. }
  34729. };
  34730. /**
  34731. * Specifies if two material defines are equal
  34732. * @param other - A material define instance to compare to
  34733. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34734. */
  34735. MaterialDefines.prototype.isEqual = function (other) {
  34736. if (this._keys.length !== other._keys.length) {
  34737. return false;
  34738. }
  34739. for (var index = 0; index < this._keys.length; index++) {
  34740. var prop = this._keys[index];
  34741. if (this[prop] !== other[prop]) {
  34742. return false;
  34743. }
  34744. }
  34745. return true;
  34746. };
  34747. /**
  34748. * Clones this instance's defines to another instance
  34749. * @param other - material defines to clone values to
  34750. */
  34751. MaterialDefines.prototype.cloneTo = function (other) {
  34752. if (this._keys.length !== other._keys.length) {
  34753. other._keys = this._keys.slice(0);
  34754. }
  34755. for (var index = 0; index < this._keys.length; index++) {
  34756. var prop = this._keys[index];
  34757. other[prop] = this[prop];
  34758. }
  34759. };
  34760. /**
  34761. * Resets the material define values
  34762. */
  34763. MaterialDefines.prototype.reset = function () {
  34764. for (var index = 0; index < this._keys.length; index++) {
  34765. var prop = this._keys[index];
  34766. var type = typeof this[prop];
  34767. switch (type) {
  34768. case "number":
  34769. this[prop] = 0;
  34770. break;
  34771. case "string":
  34772. this[prop] = "";
  34773. break;
  34774. default:
  34775. this[prop] = false;
  34776. break;
  34777. }
  34778. }
  34779. };
  34780. /**
  34781. * Converts the material define values to a string
  34782. * @returns - String of material define information
  34783. */
  34784. MaterialDefines.prototype.toString = function () {
  34785. var result = "";
  34786. for (var index = 0; index < this._keys.length; index++) {
  34787. var prop = this._keys[index];
  34788. var value = this[prop];
  34789. var type = typeof value;
  34790. switch (type) {
  34791. case "number":
  34792. case "string":
  34793. result += "#define " + prop + " " + value + "\n";
  34794. break;
  34795. default:
  34796. if (value) {
  34797. result += "#define " + prop + "\n";
  34798. }
  34799. break;
  34800. }
  34801. }
  34802. return result;
  34803. };
  34804. return MaterialDefines;
  34805. }());
  34806. BABYLON.MaterialDefines = MaterialDefines;
  34807. /**
  34808. * Base class for the main features of a material in Babylon.js
  34809. */
  34810. var Material = /** @class */ (function () {
  34811. /**
  34812. * Creates a material instance
  34813. * @param name defines the name of the material
  34814. * @param scene defines the scene to reference
  34815. * @param doNotAdd specifies if the material should be added to the scene
  34816. */
  34817. function Material(name, scene, doNotAdd) {
  34818. /**
  34819. * Specifies if the ready state should be checked on each call
  34820. */
  34821. this.checkReadyOnEveryCall = false;
  34822. /**
  34823. * Specifies if the ready state should be checked once
  34824. */
  34825. this.checkReadyOnlyOnce = false;
  34826. /**
  34827. * The state of the material
  34828. */
  34829. this.state = "";
  34830. /**
  34831. * The alpha value of the material
  34832. */
  34833. this._alpha = 1.0;
  34834. /**
  34835. * Specifies if back face culling is enabled
  34836. */
  34837. this._backFaceCulling = true;
  34838. /**
  34839. * Specifies if the material should be serialized
  34840. */
  34841. this.doNotSerialize = false;
  34842. /**
  34843. * Specifies if the effect should be stored on sub meshes
  34844. */
  34845. this.storeEffectOnSubMeshes = false;
  34846. /**
  34847. * An event triggered when the material is disposed
  34848. */
  34849. this.onDisposeObservable = new BABYLON.Observable();
  34850. /**
  34851. * Stores the value of the alpha mode
  34852. */
  34853. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34854. /**
  34855. * Stores the state of the need depth pre-pass value
  34856. */
  34857. this._needDepthPrePass = false;
  34858. /**
  34859. * Specifies if depth writing should be disabled
  34860. */
  34861. this.disableDepthWrite = false;
  34862. /**
  34863. * Specifies if depth writing should be forced
  34864. */
  34865. this.forceDepthWrite = false;
  34866. /**
  34867. * Specifies if there should be a separate pass for culling
  34868. */
  34869. this.separateCullingPass = false;
  34870. /**
  34871. * Stores the state specifing if fog should be enabled
  34872. */
  34873. this._fogEnabled = true;
  34874. /**
  34875. * Stores the size of points
  34876. */
  34877. this.pointSize = 1.0;
  34878. /**
  34879. * Stores the z offset value
  34880. */
  34881. this.zOffset = 0;
  34882. /**
  34883. * @hidden
  34884. * Specifies if the material was previously ready
  34885. */
  34886. this._wasPreviouslyReady = false;
  34887. /**
  34888. * Stores the fill mode state
  34889. */
  34890. this._fillMode = Material.TriangleFillMode;
  34891. this.name = name;
  34892. this.id = name || BABYLON.Tools.RandomId();
  34893. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34894. this.uniqueId = this._scene.getUniqueId();
  34895. if (this._scene.useRightHandedSystem) {
  34896. this.sideOrientation = Material.ClockWiseSideOrientation;
  34897. }
  34898. else {
  34899. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34900. }
  34901. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34902. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34903. if (!doNotAdd) {
  34904. this._scene.materials.push(this);
  34905. }
  34906. }
  34907. Object.defineProperty(Material, "TriangleFillMode", {
  34908. /**
  34909. * Returns the triangle fill mode
  34910. */
  34911. get: function () {
  34912. return Material._TriangleFillMode;
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(Material, "WireFrameFillMode", {
  34918. /**
  34919. * Returns the wireframe mode
  34920. */
  34921. get: function () {
  34922. return Material._WireFrameFillMode;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(Material, "PointFillMode", {
  34928. /**
  34929. * Returns the point fill mode
  34930. */
  34931. get: function () {
  34932. return Material._PointFillMode;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. Object.defineProperty(Material, "PointListDrawMode", {
  34938. /**
  34939. * Returns the point list draw mode
  34940. */
  34941. get: function () {
  34942. return Material._PointListDrawMode;
  34943. },
  34944. enumerable: true,
  34945. configurable: true
  34946. });
  34947. Object.defineProperty(Material, "LineListDrawMode", {
  34948. /**
  34949. * Returns the line list draw mode
  34950. */
  34951. get: function () {
  34952. return Material._LineListDrawMode;
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(Material, "LineLoopDrawMode", {
  34958. /**
  34959. * Returns the line loop draw mode
  34960. */
  34961. get: function () {
  34962. return Material._LineLoopDrawMode;
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. Object.defineProperty(Material, "LineStripDrawMode", {
  34968. /**
  34969. * Returns the line strip draw mode
  34970. */
  34971. get: function () {
  34972. return Material._LineStripDrawMode;
  34973. },
  34974. enumerable: true,
  34975. configurable: true
  34976. });
  34977. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34978. /**
  34979. * Returns the triangle strip draw mode
  34980. */
  34981. get: function () {
  34982. return Material._TriangleStripDrawMode;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34988. /**
  34989. * Returns the triangle fan draw mode
  34990. */
  34991. get: function () {
  34992. return Material._TriangleFanDrawMode;
  34993. },
  34994. enumerable: true,
  34995. configurable: true
  34996. });
  34997. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34998. /**
  34999. * Returns the clock-wise side orientation
  35000. */
  35001. get: function () {
  35002. return Material._ClockWiseSideOrientation;
  35003. },
  35004. enumerable: true,
  35005. configurable: true
  35006. });
  35007. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35008. /**
  35009. * Returns the counter clock-wise side orientation
  35010. */
  35011. get: function () {
  35012. return Material._CounterClockWiseSideOrientation;
  35013. },
  35014. enumerable: true,
  35015. configurable: true
  35016. });
  35017. Object.defineProperty(Material, "TextureDirtyFlag", {
  35018. /**
  35019. * Returns the dirty texture flag value
  35020. */
  35021. get: function () {
  35022. return Material._TextureDirtyFlag;
  35023. },
  35024. enumerable: true,
  35025. configurable: true
  35026. });
  35027. Object.defineProperty(Material, "LightDirtyFlag", {
  35028. /**
  35029. * Returns the dirty light flag value
  35030. */
  35031. get: function () {
  35032. return Material._LightDirtyFlag;
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35038. /**
  35039. * Returns the dirty fresnel flag value
  35040. */
  35041. get: function () {
  35042. return Material._FresnelDirtyFlag;
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35048. /**
  35049. * Returns the dirty attributes flag value
  35050. */
  35051. get: function () {
  35052. return Material._AttributesDirtyFlag;
  35053. },
  35054. enumerable: true,
  35055. configurable: true
  35056. });
  35057. Object.defineProperty(Material, "MiscDirtyFlag", {
  35058. /**
  35059. * Returns the dirty misc flag value
  35060. */
  35061. get: function () {
  35062. return Material._MiscDirtyFlag;
  35063. },
  35064. enumerable: true,
  35065. configurable: true
  35066. });
  35067. Object.defineProperty(Material.prototype, "alpha", {
  35068. /**
  35069. * Gets the alpha value of the material
  35070. */
  35071. get: function () {
  35072. return this._alpha;
  35073. },
  35074. /**
  35075. * Sets the alpha value of the material
  35076. */
  35077. set: function (value) {
  35078. if (this._alpha === value) {
  35079. return;
  35080. }
  35081. this._alpha = value;
  35082. this.markAsDirty(Material.MiscDirtyFlag);
  35083. },
  35084. enumerable: true,
  35085. configurable: true
  35086. });
  35087. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35088. /**
  35089. * Gets the back-face culling state
  35090. */
  35091. get: function () {
  35092. return this._backFaceCulling;
  35093. },
  35094. /**
  35095. * Sets the back-face culling state
  35096. */
  35097. set: function (value) {
  35098. if (this._backFaceCulling === value) {
  35099. return;
  35100. }
  35101. this._backFaceCulling = value;
  35102. this.markAsDirty(Material.TextureDirtyFlag);
  35103. },
  35104. enumerable: true,
  35105. configurable: true
  35106. });
  35107. Object.defineProperty(Material.prototype, "onDispose", {
  35108. /**
  35109. * Called during a dispose event
  35110. */
  35111. set: function (callback) {
  35112. if (this._onDisposeObserver) {
  35113. this.onDisposeObservable.remove(this._onDisposeObserver);
  35114. }
  35115. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35116. },
  35117. enumerable: true,
  35118. configurable: true
  35119. });
  35120. Object.defineProperty(Material.prototype, "onBindObservable", {
  35121. /**
  35122. * An event triggered when the material is bound
  35123. */
  35124. get: function () {
  35125. if (!this._onBindObservable) {
  35126. this._onBindObservable = new BABYLON.Observable();
  35127. }
  35128. return this._onBindObservable;
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(Material.prototype, "onBind", {
  35134. /**
  35135. * Called during a bind event
  35136. */
  35137. set: function (callback) {
  35138. if (this._onBindObserver) {
  35139. this.onBindObservable.remove(this._onBindObserver);
  35140. }
  35141. this._onBindObserver = this.onBindObservable.add(callback);
  35142. },
  35143. enumerable: true,
  35144. configurable: true
  35145. });
  35146. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35147. /**
  35148. * An event triggered when the material is unbound
  35149. */
  35150. get: function () {
  35151. if (!this._onUnBindObservable) {
  35152. this._onUnBindObservable = new BABYLON.Observable();
  35153. }
  35154. return this._onUnBindObservable;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material.prototype, "alphaMode", {
  35160. /**
  35161. * Gets the value of the alpha mode
  35162. */
  35163. get: function () {
  35164. return this._alphaMode;
  35165. },
  35166. /**
  35167. * Sets the value of the alpha mode.
  35168. *
  35169. * | Value | Type | Description |
  35170. * | --- | --- | --- |
  35171. * | 0 | ALPHA_DISABLE | |
  35172. * | 1 | ALPHA_ADD | |
  35173. * | 2 | ALPHA_COMBINE | |
  35174. * | 3 | ALPHA_SUBTRACT | |
  35175. * | 4 | ALPHA_MULTIPLY | |
  35176. * | 5 | ALPHA_MAXIMIZED | |
  35177. * | 6 | ALPHA_ONEONE | |
  35178. * | 7 | ALPHA_PREMULTIPLIED | |
  35179. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35180. * | 9 | ALPHA_INTERPOLATE | |
  35181. * | 10 | ALPHA_SCREENMODE | |
  35182. *
  35183. */
  35184. set: function (value) {
  35185. if (this._alphaMode === value) {
  35186. return;
  35187. }
  35188. this._alphaMode = value;
  35189. this.markAsDirty(Material.TextureDirtyFlag);
  35190. },
  35191. enumerable: true,
  35192. configurable: true
  35193. });
  35194. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35195. /**
  35196. * Gets the depth pre-pass value
  35197. */
  35198. get: function () {
  35199. return this._needDepthPrePass;
  35200. },
  35201. /**
  35202. * Sets the need depth pre-pass value
  35203. */
  35204. set: function (value) {
  35205. if (this._needDepthPrePass === value) {
  35206. return;
  35207. }
  35208. this._needDepthPrePass = value;
  35209. if (this._needDepthPrePass) {
  35210. this.checkReadyOnEveryCall = true;
  35211. }
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(Material.prototype, "fogEnabled", {
  35217. /**
  35218. * Gets the value of the fog enabled state
  35219. */
  35220. get: function () {
  35221. return this._fogEnabled;
  35222. },
  35223. /**
  35224. * Sets the state for enabling fog
  35225. */
  35226. set: function (value) {
  35227. if (this._fogEnabled === value) {
  35228. return;
  35229. }
  35230. this._fogEnabled = value;
  35231. this.markAsDirty(Material.MiscDirtyFlag);
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(Material.prototype, "wireframe", {
  35237. /**
  35238. * Gets a value specifying if wireframe mode is enabled
  35239. */
  35240. get: function () {
  35241. switch (this._fillMode) {
  35242. case Material.WireFrameFillMode:
  35243. case Material.LineListDrawMode:
  35244. case Material.LineLoopDrawMode:
  35245. case Material.LineStripDrawMode:
  35246. return true;
  35247. }
  35248. return this._scene.forceWireframe;
  35249. },
  35250. /**
  35251. * Sets the state of wireframe mode
  35252. */
  35253. set: function (value) {
  35254. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35255. },
  35256. enumerable: true,
  35257. configurable: true
  35258. });
  35259. Object.defineProperty(Material.prototype, "pointsCloud", {
  35260. /**
  35261. * Gets the value specifying if point clouds are enabled
  35262. */
  35263. get: function () {
  35264. switch (this._fillMode) {
  35265. case Material.PointFillMode:
  35266. case Material.PointListDrawMode:
  35267. return true;
  35268. }
  35269. return this._scene.forcePointsCloud;
  35270. },
  35271. /**
  35272. * Sets the state of point cloud mode
  35273. */
  35274. set: function (value) {
  35275. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. Object.defineProperty(Material.prototype, "fillMode", {
  35281. /**
  35282. * Gets the material fill mode
  35283. */
  35284. get: function () {
  35285. return this._fillMode;
  35286. },
  35287. /**
  35288. * Sets the material fill mode
  35289. */
  35290. set: function (value) {
  35291. if (this._fillMode === value) {
  35292. return;
  35293. }
  35294. this._fillMode = value;
  35295. this.markAsDirty(Material.MiscDirtyFlag);
  35296. },
  35297. enumerable: true,
  35298. configurable: true
  35299. });
  35300. /**
  35301. * Returns a string representation of the current material
  35302. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35303. * @returns a string with material information
  35304. */
  35305. Material.prototype.toString = function (fullDetails) {
  35306. var ret = "Name: " + this.name;
  35307. if (fullDetails) {
  35308. }
  35309. return ret;
  35310. };
  35311. /**
  35312. * Gets the class name of the material
  35313. * @returns a string with the class name of the material
  35314. */
  35315. Material.prototype.getClassName = function () {
  35316. return "Material";
  35317. };
  35318. Object.defineProperty(Material.prototype, "isFrozen", {
  35319. /**
  35320. * Specifies if updates for the material been locked
  35321. */
  35322. get: function () {
  35323. return this.checkReadyOnlyOnce;
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. /**
  35329. * Locks updates for the material
  35330. */
  35331. Material.prototype.freeze = function () {
  35332. this.checkReadyOnlyOnce = true;
  35333. };
  35334. /**
  35335. * Unlocks updates for the material
  35336. */
  35337. Material.prototype.unfreeze = function () {
  35338. this.checkReadyOnlyOnce = false;
  35339. };
  35340. /**
  35341. * Specifies if the material is ready to be used
  35342. * @param mesh defines the mesh to check
  35343. * @param useInstances specifies if instances should be used
  35344. * @returns a boolean indicating if the material is ready to be used
  35345. */
  35346. Material.prototype.isReady = function (mesh, useInstances) {
  35347. return true;
  35348. };
  35349. /**
  35350. * Specifies that the submesh is ready to be used
  35351. * @param mesh defines the mesh to check
  35352. * @param subMesh defines which submesh to check
  35353. * @param useInstances specifies that instances should be used
  35354. * @returns a boolean indicating that the submesh is ready or not
  35355. */
  35356. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35357. return false;
  35358. };
  35359. /**
  35360. * Returns the material effect
  35361. * @returns the effect associated with the material
  35362. */
  35363. Material.prototype.getEffect = function () {
  35364. return this._effect;
  35365. };
  35366. /**
  35367. * Returns the current scene
  35368. * @returns a Scene
  35369. */
  35370. Material.prototype.getScene = function () {
  35371. return this._scene;
  35372. };
  35373. /**
  35374. * Specifies if the material will require alpha blending
  35375. * @returns a boolean specifying if alpha blending is needed
  35376. */
  35377. Material.prototype.needAlphaBlending = function () {
  35378. return (this.alpha < 1.0);
  35379. };
  35380. /**
  35381. * Specifies if the mesh will require alpha blending
  35382. * @param mesh defines the mesh to check
  35383. * @returns a boolean specifying if alpha blending is needed for the mesh
  35384. */
  35385. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35386. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35387. };
  35388. /**
  35389. * Specifies if this material should be rendered in alpha test mode
  35390. * @returns a boolean specifying if an alpha test is needed.
  35391. */
  35392. Material.prototype.needAlphaTesting = function () {
  35393. return false;
  35394. };
  35395. /**
  35396. * Gets the texture used for the alpha test
  35397. * @returns the texture to use for alpha testing
  35398. */
  35399. Material.prototype.getAlphaTestTexture = function () {
  35400. return null;
  35401. };
  35402. /**
  35403. * Marks the material to indicate that it needs to be re-calculated
  35404. */
  35405. Material.prototype.markDirty = function () {
  35406. this._wasPreviouslyReady = false;
  35407. };
  35408. /** @hidden */
  35409. Material.prototype._preBind = function (effect, overrideOrientation) {
  35410. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35411. var engine = this._scene.getEngine();
  35412. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35413. var reverse = orientation === Material.ClockWiseSideOrientation;
  35414. engine.enableEffect(effect ? effect : this._effect);
  35415. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35416. return reverse;
  35417. };
  35418. /**
  35419. * Binds the material to the mesh
  35420. * @param world defines the world transformation matrix
  35421. * @param mesh defines the mesh to bind the material to
  35422. */
  35423. Material.prototype.bind = function (world, mesh) {
  35424. };
  35425. /**
  35426. * Binds the submesh to the material
  35427. * @param world defines the world transformation matrix
  35428. * @param mesh defines the mesh containing the submesh
  35429. * @param subMesh defines the submesh to bind the material to
  35430. */
  35431. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35432. };
  35433. /**
  35434. * Binds the world matrix to the material
  35435. * @param world defines the world transformation matrix
  35436. */
  35437. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35438. };
  35439. /**
  35440. * Binds the scene's uniform buffer to the effect.
  35441. * @param effect defines the effect to bind to the scene uniform buffer
  35442. * @param sceneUbo defines the uniform buffer storing scene data
  35443. */
  35444. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35445. sceneUbo.bindToEffect(effect, "Scene");
  35446. };
  35447. /**
  35448. * Binds the view matrix to the effect
  35449. * @param effect defines the effect to bind the view matrix to
  35450. */
  35451. Material.prototype.bindView = function (effect) {
  35452. if (!this._useUBO) {
  35453. effect.setMatrix("view", this.getScene().getViewMatrix());
  35454. }
  35455. else {
  35456. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35457. }
  35458. };
  35459. /**
  35460. * Binds the view projection matrix to the effect
  35461. * @param effect defines the effect to bind the view projection matrix to
  35462. */
  35463. Material.prototype.bindViewProjection = function (effect) {
  35464. if (!this._useUBO) {
  35465. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35466. }
  35467. else {
  35468. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35469. }
  35470. };
  35471. /**
  35472. * Specifies if material alpha testing should be turned on for the mesh
  35473. * @param mesh defines the mesh to check
  35474. */
  35475. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35476. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35477. };
  35478. /**
  35479. * Processes to execute after binding the material to a mesh
  35480. * @param mesh defines the rendered mesh
  35481. */
  35482. Material.prototype._afterBind = function (mesh) {
  35483. this._scene._cachedMaterial = this;
  35484. if (mesh) {
  35485. this._scene._cachedVisibility = mesh.visibility;
  35486. }
  35487. else {
  35488. this._scene._cachedVisibility = 1;
  35489. }
  35490. if (this._onBindObservable && mesh) {
  35491. this._onBindObservable.notifyObservers(mesh);
  35492. }
  35493. if (this.disableDepthWrite) {
  35494. var engine = this._scene.getEngine();
  35495. this._cachedDepthWriteState = engine.getDepthWrite();
  35496. engine.setDepthWrite(false);
  35497. }
  35498. };
  35499. /**
  35500. * Unbinds the material from the mesh
  35501. */
  35502. Material.prototype.unbind = function () {
  35503. if (this._onUnBindObservable) {
  35504. this._onUnBindObservable.notifyObservers(this);
  35505. }
  35506. if (this.disableDepthWrite) {
  35507. var engine = this._scene.getEngine();
  35508. engine.setDepthWrite(this._cachedDepthWriteState);
  35509. }
  35510. };
  35511. /**
  35512. * Gets the active textures from the material
  35513. * @returns an array of textures
  35514. */
  35515. Material.prototype.getActiveTextures = function () {
  35516. return [];
  35517. };
  35518. /**
  35519. * Specifies if the material uses a texture
  35520. * @param texture defines the texture to check against the material
  35521. * @returns a boolean specifying if the material uses the texture
  35522. */
  35523. Material.prototype.hasTexture = function (texture) {
  35524. return false;
  35525. };
  35526. /**
  35527. * Makes a duplicate of the material, and gives it a new name
  35528. * @param name defines the new name for the duplicated material
  35529. * @returns the cloned material
  35530. */
  35531. Material.prototype.clone = function (name) {
  35532. return null;
  35533. };
  35534. /**
  35535. * Gets the meshes bound to the material
  35536. * @returns an array of meshes bound to the material
  35537. */
  35538. Material.prototype.getBindedMeshes = function () {
  35539. var result = new Array();
  35540. for (var index = 0; index < this._scene.meshes.length; index++) {
  35541. var mesh = this._scene.meshes[index];
  35542. if (mesh.material === this) {
  35543. result.push(mesh);
  35544. }
  35545. }
  35546. return result;
  35547. };
  35548. /**
  35549. * Force shader compilation
  35550. * @param mesh defines the mesh associated with this material
  35551. * @param onCompiled defines a function to execute once the material is compiled
  35552. * @param options defines the options to configure the compilation
  35553. */
  35554. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35555. var _this = this;
  35556. var localOptions = __assign({ clipPlane: false }, options);
  35557. var subMesh = new BABYLON.BaseSubMesh();
  35558. var scene = this.getScene();
  35559. var checkReady = function () {
  35560. if (!_this._scene || !_this._scene.getEngine()) {
  35561. return;
  35562. }
  35563. if (subMesh._materialDefines) {
  35564. subMesh._materialDefines._renderId = -1;
  35565. }
  35566. var clipPlaneState = scene.clipPlane;
  35567. if (localOptions.clipPlane) {
  35568. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35569. }
  35570. if (_this.storeEffectOnSubMeshes) {
  35571. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35572. if (onCompiled) {
  35573. onCompiled(_this);
  35574. }
  35575. }
  35576. else {
  35577. setTimeout(checkReady, 16);
  35578. }
  35579. }
  35580. else {
  35581. if (_this.isReady(mesh)) {
  35582. if (onCompiled) {
  35583. onCompiled(_this);
  35584. }
  35585. }
  35586. else {
  35587. setTimeout(checkReady, 16);
  35588. }
  35589. }
  35590. if (localOptions.clipPlane) {
  35591. scene.clipPlane = clipPlaneState;
  35592. }
  35593. };
  35594. checkReady();
  35595. };
  35596. /**
  35597. * Force shader compilation
  35598. * @param mesh defines the mesh that will use this material
  35599. * @param options defines additional options for compiling the shaders
  35600. * @returns a promise that resolves when the compilation completes
  35601. */
  35602. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35603. var _this = this;
  35604. return new Promise(function (resolve) {
  35605. _this.forceCompilation(mesh, function () {
  35606. resolve();
  35607. }, options);
  35608. });
  35609. };
  35610. /**
  35611. * Marks a define in the material to indicate that it needs to be re-computed
  35612. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35613. */
  35614. Material.prototype.markAsDirty = function (flag) {
  35615. if (flag & Material.TextureDirtyFlag) {
  35616. this._markAllSubMeshesAsTexturesDirty();
  35617. }
  35618. if (flag & Material.LightDirtyFlag) {
  35619. this._markAllSubMeshesAsLightsDirty();
  35620. }
  35621. if (flag & Material.FresnelDirtyFlag) {
  35622. this._markAllSubMeshesAsFresnelDirty();
  35623. }
  35624. if (flag & Material.AttributesDirtyFlag) {
  35625. this._markAllSubMeshesAsAttributesDirty();
  35626. }
  35627. if (flag & Material.MiscDirtyFlag) {
  35628. this._markAllSubMeshesAsMiscDirty();
  35629. }
  35630. this.getScene().resetCachedMaterial();
  35631. };
  35632. /**
  35633. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35634. * @param func defines a function which checks material defines against the submeshes
  35635. */
  35636. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35637. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35638. var mesh = _a[_i];
  35639. if (!mesh.subMeshes) {
  35640. continue;
  35641. }
  35642. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35643. var subMesh = _c[_b];
  35644. if (subMesh.getMaterial() !== this) {
  35645. continue;
  35646. }
  35647. if (!subMesh._materialDefines) {
  35648. continue;
  35649. }
  35650. func(subMesh._materialDefines);
  35651. }
  35652. }
  35653. };
  35654. /**
  35655. * Indicates that image processing needs to be re-calculated for all submeshes
  35656. */
  35657. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35658. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35659. };
  35660. /**
  35661. * Indicates that textures need to be re-calculated for all submeshes
  35662. */
  35663. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35664. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35665. };
  35666. /**
  35667. * Indicates that fresnel needs to be re-calculated for all submeshes
  35668. */
  35669. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35670. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35671. };
  35672. /**
  35673. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35674. */
  35675. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35676. this._markAllSubMeshesAsDirty(function (defines) {
  35677. defines.markAsFresnelDirty();
  35678. defines.markAsMiscDirty();
  35679. });
  35680. };
  35681. /**
  35682. * Indicates that lights need to be re-calculated for all submeshes
  35683. */
  35684. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35685. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35686. };
  35687. /**
  35688. * Indicates that attributes need to be re-calculated for all submeshes
  35689. */
  35690. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35691. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35692. };
  35693. /**
  35694. * Indicates that misc needs to be re-calculated for all submeshes
  35695. */
  35696. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35697. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35698. };
  35699. /**
  35700. * Indicates that textures and misc need to be re-calculated for all submeshes
  35701. */
  35702. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35703. this._markAllSubMeshesAsDirty(function (defines) {
  35704. defines.markAsTexturesDirty();
  35705. defines.markAsMiscDirty();
  35706. });
  35707. };
  35708. /**
  35709. * Disposes the material
  35710. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35711. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35712. */
  35713. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35714. // Animations
  35715. this.getScene().stopAnimation(this);
  35716. this.getScene().freeProcessedMaterials();
  35717. // Remove from scene
  35718. var index = this._scene.materials.indexOf(this);
  35719. if (index >= 0) {
  35720. this._scene.materials.splice(index, 1);
  35721. }
  35722. // Remove from meshes
  35723. for (index = 0; index < this._scene.meshes.length; index++) {
  35724. var mesh = this._scene.meshes[index];
  35725. if (mesh.material === this) {
  35726. mesh.material = null;
  35727. if (mesh.geometry) {
  35728. var geometry = (mesh.geometry);
  35729. if (this.storeEffectOnSubMeshes) {
  35730. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35731. var subMesh = _a[_i];
  35732. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35733. if (forceDisposeEffect && subMesh._materialEffect) {
  35734. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35735. }
  35736. }
  35737. }
  35738. else {
  35739. geometry._releaseVertexArrayObject(this._effect);
  35740. }
  35741. }
  35742. }
  35743. }
  35744. this._uniformBuffer.dispose();
  35745. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35746. if (forceDisposeEffect && this._effect) {
  35747. if (!this.storeEffectOnSubMeshes) {
  35748. this._scene.getEngine()._releaseEffect(this._effect);
  35749. }
  35750. this._effect = null;
  35751. }
  35752. // Callback
  35753. this.onDisposeObservable.notifyObservers(this);
  35754. this.onDisposeObservable.clear();
  35755. if (this._onBindObservable) {
  35756. this._onBindObservable.clear();
  35757. }
  35758. if (this._onUnBindObservable) {
  35759. this._onUnBindObservable.clear();
  35760. }
  35761. };
  35762. /**
  35763. * Serializes this material
  35764. * @returns the serialized material object
  35765. */
  35766. Material.prototype.serialize = function () {
  35767. return BABYLON.SerializationHelper.Serialize(this);
  35768. };
  35769. /**
  35770. * Creates a MultiMaterial from parsed MultiMaterial data.
  35771. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35772. * @param scene defines the hosting scene
  35773. * @returns a new MultiMaterial
  35774. */
  35775. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35776. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35777. multiMaterial.id = parsedMultiMaterial.id;
  35778. if (BABYLON.Tags) {
  35779. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35780. }
  35781. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35782. var subMatId = parsedMultiMaterial.materials[matIndex];
  35783. if (subMatId) {
  35784. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35785. }
  35786. else {
  35787. multiMaterial.subMaterials.push(null);
  35788. }
  35789. }
  35790. return multiMaterial;
  35791. };
  35792. /**
  35793. * Creates a material from parsed material data
  35794. * @param parsedMaterial defines parsed material data
  35795. * @param scene defines the hosting scene
  35796. * @param rootUrl defines the root URL to use to load textures
  35797. * @returns a new material
  35798. */
  35799. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35800. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35801. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35802. }
  35803. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35804. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35805. if (!BABYLON.LegacyPBRMaterial) {
  35806. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35807. return;
  35808. }
  35809. }
  35810. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35811. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35812. };
  35813. // Triangle views
  35814. Material._TriangleFillMode = 0;
  35815. Material._WireFrameFillMode = 1;
  35816. Material._PointFillMode = 2;
  35817. // Draw modes
  35818. Material._PointListDrawMode = 3;
  35819. Material._LineListDrawMode = 4;
  35820. Material._LineLoopDrawMode = 5;
  35821. Material._LineStripDrawMode = 6;
  35822. Material._TriangleStripDrawMode = 7;
  35823. Material._TriangleFanDrawMode = 8;
  35824. /**
  35825. * Stores the clock-wise side orientation
  35826. */
  35827. Material._ClockWiseSideOrientation = 0;
  35828. /**
  35829. * Stores the counter clock-wise side orientation
  35830. */
  35831. Material._CounterClockWiseSideOrientation = 1;
  35832. /**
  35833. * The dirty texture flag value
  35834. */
  35835. Material._TextureDirtyFlag = 1;
  35836. /**
  35837. * The dirty light flag value
  35838. */
  35839. Material._LightDirtyFlag = 2;
  35840. /**
  35841. * The dirty fresnel flag value
  35842. */
  35843. Material._FresnelDirtyFlag = 4;
  35844. /**
  35845. * The dirty attribute flag value
  35846. */
  35847. Material._AttributesDirtyFlag = 8;
  35848. /**
  35849. * The dirty misc flag value
  35850. */
  35851. Material._MiscDirtyFlag = 16;
  35852. __decorate([
  35853. BABYLON.serialize()
  35854. ], Material.prototype, "id", void 0);
  35855. __decorate([
  35856. BABYLON.serialize()
  35857. ], Material.prototype, "uniqueId", void 0);
  35858. __decorate([
  35859. BABYLON.serialize()
  35860. ], Material.prototype, "name", void 0);
  35861. __decorate([
  35862. BABYLON.serialize()
  35863. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35864. __decorate([
  35865. BABYLON.serialize()
  35866. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35867. __decorate([
  35868. BABYLON.serialize()
  35869. ], Material.prototype, "state", void 0);
  35870. __decorate([
  35871. BABYLON.serialize("alpha")
  35872. ], Material.prototype, "_alpha", void 0);
  35873. __decorate([
  35874. BABYLON.serialize("backFaceCulling")
  35875. ], Material.prototype, "_backFaceCulling", void 0);
  35876. __decorate([
  35877. BABYLON.serialize()
  35878. ], Material.prototype, "sideOrientation", void 0);
  35879. __decorate([
  35880. BABYLON.serialize("alphaMode")
  35881. ], Material.prototype, "_alphaMode", void 0);
  35882. __decorate([
  35883. BABYLON.serialize()
  35884. ], Material.prototype, "_needDepthPrePass", void 0);
  35885. __decorate([
  35886. BABYLON.serialize()
  35887. ], Material.prototype, "disableDepthWrite", void 0);
  35888. __decorate([
  35889. BABYLON.serialize()
  35890. ], Material.prototype, "forceDepthWrite", void 0);
  35891. __decorate([
  35892. BABYLON.serialize()
  35893. ], Material.prototype, "separateCullingPass", void 0);
  35894. __decorate([
  35895. BABYLON.serialize("fogEnabled")
  35896. ], Material.prototype, "_fogEnabled", void 0);
  35897. __decorate([
  35898. BABYLON.serialize()
  35899. ], Material.prototype, "pointSize", void 0);
  35900. __decorate([
  35901. BABYLON.serialize()
  35902. ], Material.prototype, "zOffset", void 0);
  35903. __decorate([
  35904. BABYLON.serialize()
  35905. ], Material.prototype, "wireframe", null);
  35906. __decorate([
  35907. BABYLON.serialize()
  35908. ], Material.prototype, "pointsCloud", null);
  35909. __decorate([
  35910. BABYLON.serialize()
  35911. ], Material.prototype, "fillMode", null);
  35912. return Material;
  35913. }());
  35914. BABYLON.Material = Material;
  35915. })(BABYLON || (BABYLON = {}));
  35916. //# sourceMappingURL=babylon.material.js.map
  35917. var BABYLON;
  35918. (function (BABYLON) {
  35919. var UniformBuffer = /** @class */ (function () {
  35920. /**
  35921. * Uniform buffer objects.
  35922. *
  35923. * Handles blocks of uniform on the GPU.
  35924. *
  35925. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35926. *
  35927. * For more information, please refer to :
  35928. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35929. */
  35930. function UniformBuffer(engine, data, dynamic) {
  35931. this._engine = engine;
  35932. this._noUBO = !engine.supportsUniformBuffers;
  35933. this._dynamic = dynamic;
  35934. this._data = data || [];
  35935. this._uniformLocations = {};
  35936. this._uniformSizes = {};
  35937. this._uniformLocationPointer = 0;
  35938. this._needSync = false;
  35939. if (this._noUBO) {
  35940. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35941. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35942. this.updateFloat = this._updateFloatForEffect;
  35943. this.updateFloat2 = this._updateFloat2ForEffect;
  35944. this.updateFloat3 = this._updateFloat3ForEffect;
  35945. this.updateFloat4 = this._updateFloat4ForEffect;
  35946. this.updateMatrix = this._updateMatrixForEffect;
  35947. this.updateVector3 = this._updateVector3ForEffect;
  35948. this.updateVector4 = this._updateVector4ForEffect;
  35949. this.updateColor3 = this._updateColor3ForEffect;
  35950. this.updateColor4 = this._updateColor4ForEffect;
  35951. }
  35952. else {
  35953. this._engine._uniformBuffers.push(this);
  35954. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35955. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35956. this.updateFloat = this._updateFloatForUniform;
  35957. this.updateFloat2 = this._updateFloat2ForUniform;
  35958. this.updateFloat3 = this._updateFloat3ForUniform;
  35959. this.updateFloat4 = this._updateFloat4ForUniform;
  35960. this.updateMatrix = this._updateMatrixForUniform;
  35961. this.updateVector3 = this._updateVector3ForUniform;
  35962. this.updateVector4 = this._updateVector4ForUniform;
  35963. this.updateColor3 = this._updateColor3ForUniform;
  35964. this.updateColor4 = this._updateColor4ForUniform;
  35965. }
  35966. }
  35967. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35968. // Properties
  35969. /**
  35970. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35971. * or just falling back on setUniformXXX calls.
  35972. */
  35973. get: function () {
  35974. return !this._noUBO;
  35975. },
  35976. enumerable: true,
  35977. configurable: true
  35978. });
  35979. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35980. /**
  35981. * Indicates if the WebGL underlying uniform buffer is in sync
  35982. * with the javascript cache data.
  35983. */
  35984. get: function () {
  35985. return !this._needSync;
  35986. },
  35987. enumerable: true,
  35988. configurable: true
  35989. });
  35990. /**
  35991. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35992. * Also, a dynamic UniformBuffer will disable cache verification and always
  35993. * update the underlying WebGL uniform buffer to the GPU.
  35994. */
  35995. UniformBuffer.prototype.isDynamic = function () {
  35996. return this._dynamic !== undefined;
  35997. };
  35998. /**
  35999. * The data cache on JS side.
  36000. */
  36001. UniformBuffer.prototype.getData = function () {
  36002. return this._bufferData;
  36003. };
  36004. /**
  36005. * The underlying WebGL Uniform buffer.
  36006. */
  36007. UniformBuffer.prototype.getBuffer = function () {
  36008. return this._buffer;
  36009. };
  36010. /**
  36011. * std140 layout specifies how to align data within an UBO structure.
  36012. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36013. * for specs.
  36014. */
  36015. UniformBuffer.prototype._fillAlignment = function (size) {
  36016. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36017. // and 4x4 matrices
  36018. // TODO : change if other types are used
  36019. var alignment;
  36020. if (size <= 2) {
  36021. alignment = size;
  36022. }
  36023. else {
  36024. alignment = 4;
  36025. }
  36026. if ((this._uniformLocationPointer % alignment) !== 0) {
  36027. var oldPointer = this._uniformLocationPointer;
  36028. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36029. var diff = this._uniformLocationPointer - oldPointer;
  36030. for (var i = 0; i < diff; i++) {
  36031. this._data.push(0);
  36032. }
  36033. }
  36034. };
  36035. /**
  36036. * Adds an uniform in the buffer.
  36037. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36038. * for the layout to be correct !
  36039. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36040. * @param {number|number[]} size Data size, or data directly.
  36041. */
  36042. UniformBuffer.prototype.addUniform = function (name, size) {
  36043. if (this._noUBO) {
  36044. return;
  36045. }
  36046. if (this._uniformLocations[name] !== undefined) {
  36047. // Already existing uniform
  36048. return;
  36049. }
  36050. // This function must be called in the order of the shader layout !
  36051. // size can be the size of the uniform, or data directly
  36052. var data;
  36053. if (size instanceof Array) {
  36054. data = size;
  36055. size = data.length;
  36056. }
  36057. else {
  36058. size = size;
  36059. data = [];
  36060. // Fill with zeros
  36061. for (var i = 0; i < size; i++) {
  36062. data.push(0);
  36063. }
  36064. }
  36065. this._fillAlignment(size);
  36066. this._uniformSizes[name] = size;
  36067. this._uniformLocations[name] = this._uniformLocationPointer;
  36068. this._uniformLocationPointer += size;
  36069. for (var i = 0; i < size; i++) {
  36070. this._data.push(data[i]);
  36071. }
  36072. this._needSync = true;
  36073. };
  36074. /**
  36075. * Wrapper for addUniform.
  36076. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36077. * @param {Matrix} mat A 4x4 matrix.
  36078. */
  36079. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36080. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36081. };
  36082. /**
  36083. * Wrapper for addUniform.
  36084. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36085. * @param {number} x
  36086. * @param {number} y
  36087. */
  36088. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36089. var temp = [x, y];
  36090. this.addUniform(name, temp);
  36091. };
  36092. /**
  36093. * Wrapper for addUniform.
  36094. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36095. * @param {number} x
  36096. * @param {number} y
  36097. * @param {number} z
  36098. */
  36099. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36100. var temp = [x, y, z];
  36101. this.addUniform(name, temp);
  36102. };
  36103. /**
  36104. * Wrapper for addUniform.
  36105. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36106. * @param {Color3} color
  36107. */
  36108. UniformBuffer.prototype.addColor3 = function (name, color) {
  36109. var temp = new Array();
  36110. color.toArray(temp);
  36111. this.addUniform(name, temp);
  36112. };
  36113. /**
  36114. * Wrapper for addUniform.
  36115. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36116. * @param {Color3} color
  36117. * @param {number} alpha
  36118. */
  36119. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36120. var temp = new Array();
  36121. color.toArray(temp);
  36122. temp.push(alpha);
  36123. this.addUniform(name, temp);
  36124. };
  36125. /**
  36126. * Wrapper for addUniform.
  36127. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36128. * @param {Vector3} vector
  36129. */
  36130. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36131. var temp = new Array();
  36132. vector.toArray(temp);
  36133. this.addUniform(name, temp);
  36134. };
  36135. /**
  36136. * Wrapper for addUniform.
  36137. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36138. */
  36139. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36140. this.addUniform(name, 12);
  36141. };
  36142. /**
  36143. * Wrapper for addUniform.
  36144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36145. */
  36146. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36147. this.addUniform(name, 8);
  36148. };
  36149. /**
  36150. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36151. */
  36152. UniformBuffer.prototype.create = function () {
  36153. if (this._noUBO) {
  36154. return;
  36155. }
  36156. if (this._buffer) {
  36157. return; // nothing to do
  36158. }
  36159. // See spec, alignment must be filled as a vec4
  36160. this._fillAlignment(4);
  36161. this._bufferData = new Float32Array(this._data);
  36162. this._rebuild();
  36163. this._needSync = true;
  36164. };
  36165. /** @hidden */
  36166. UniformBuffer.prototype._rebuild = function () {
  36167. if (this._noUBO) {
  36168. return;
  36169. }
  36170. if (this._dynamic) {
  36171. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36172. }
  36173. else {
  36174. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36175. }
  36176. };
  36177. /**
  36178. * Updates the WebGL Uniform Buffer on the GPU.
  36179. * If the `dynamic` flag is set to true, no cache comparison is done.
  36180. * Otherwise, the buffer will be updated only if the cache differs.
  36181. */
  36182. UniformBuffer.prototype.update = function () {
  36183. if (!this._buffer) {
  36184. this.create();
  36185. return;
  36186. }
  36187. if (!this._dynamic && !this._needSync) {
  36188. return;
  36189. }
  36190. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36191. this._needSync = false;
  36192. };
  36193. /**
  36194. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36195. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36196. * @param {number[]|Float32Array} data Flattened data
  36197. * @param {number} size Size of the data.
  36198. */
  36199. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36200. var location = this._uniformLocations[uniformName];
  36201. if (location === undefined) {
  36202. if (this._buffer) {
  36203. // Cannot add an uniform if the buffer is already created
  36204. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36205. return;
  36206. }
  36207. this.addUniform(uniformName, size);
  36208. location = this._uniformLocations[uniformName];
  36209. }
  36210. if (!this._buffer) {
  36211. this.create();
  36212. }
  36213. if (!this._dynamic) {
  36214. // Cache for static uniform buffers
  36215. var changed = false;
  36216. for (var i = 0; i < size; i++) {
  36217. if (this._bufferData[location + i] !== data[i]) {
  36218. changed = true;
  36219. this._bufferData[location + i] = data[i];
  36220. }
  36221. }
  36222. this._needSync = this._needSync || changed;
  36223. }
  36224. else {
  36225. // No cache for dynamic
  36226. for (var i = 0; i < size; i++) {
  36227. this._bufferData[location + i] = data[i];
  36228. }
  36229. }
  36230. };
  36231. // Update methods
  36232. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36233. // To match std140, matrix must be realigned
  36234. for (var i = 0; i < 3; i++) {
  36235. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36236. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36237. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36238. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36239. }
  36240. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36241. };
  36242. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36243. this._currentEffect.setMatrix3x3(name, matrix);
  36244. };
  36245. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36246. this._currentEffect.setMatrix2x2(name, matrix);
  36247. };
  36248. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36249. // To match std140, matrix must be realigned
  36250. for (var i = 0; i < 2; i++) {
  36251. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36252. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36253. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36254. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36255. }
  36256. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36257. };
  36258. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36259. this._currentEffect.setFloat(name, x);
  36260. };
  36261. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36262. UniformBuffer._tempBuffer[0] = x;
  36263. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36264. };
  36265. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36266. if (suffix === void 0) { suffix = ""; }
  36267. this._currentEffect.setFloat2(name + suffix, x, y);
  36268. };
  36269. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36270. if (suffix === void 0) { suffix = ""; }
  36271. UniformBuffer._tempBuffer[0] = x;
  36272. UniformBuffer._tempBuffer[1] = y;
  36273. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36274. };
  36275. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36276. if (suffix === void 0) { suffix = ""; }
  36277. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36278. };
  36279. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36280. if (suffix === void 0) { suffix = ""; }
  36281. UniformBuffer._tempBuffer[0] = x;
  36282. UniformBuffer._tempBuffer[1] = y;
  36283. UniformBuffer._tempBuffer[2] = z;
  36284. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36285. };
  36286. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36287. if (suffix === void 0) { suffix = ""; }
  36288. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36289. };
  36290. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36291. if (suffix === void 0) { suffix = ""; }
  36292. UniformBuffer._tempBuffer[0] = x;
  36293. UniformBuffer._tempBuffer[1] = y;
  36294. UniformBuffer._tempBuffer[2] = z;
  36295. UniformBuffer._tempBuffer[3] = w;
  36296. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36297. };
  36298. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36299. this._currentEffect.setMatrix(name, mat);
  36300. };
  36301. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36302. this.updateUniform(name, mat.toArray(), 16);
  36303. };
  36304. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36305. this._currentEffect.setVector3(name, vector);
  36306. };
  36307. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36308. vector.toArray(UniformBuffer._tempBuffer);
  36309. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36310. };
  36311. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36312. this._currentEffect.setVector4(name, vector);
  36313. };
  36314. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36315. vector.toArray(UniformBuffer._tempBuffer);
  36316. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36317. };
  36318. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36319. if (suffix === void 0) { suffix = ""; }
  36320. this._currentEffect.setColor3(name + suffix, color);
  36321. };
  36322. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36323. if (suffix === void 0) { suffix = ""; }
  36324. color.toArray(UniformBuffer._tempBuffer);
  36325. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36326. };
  36327. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36328. if (suffix === void 0) { suffix = ""; }
  36329. this._currentEffect.setColor4(name + suffix, color, alpha);
  36330. };
  36331. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36332. if (suffix === void 0) { suffix = ""; }
  36333. color.toArray(UniformBuffer._tempBuffer);
  36334. UniformBuffer._tempBuffer[3] = alpha;
  36335. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36336. };
  36337. /**
  36338. * Sets a sampler uniform on the effect.
  36339. * @param {string} name Name of the sampler.
  36340. * @param {Texture} texture
  36341. */
  36342. UniformBuffer.prototype.setTexture = function (name, texture) {
  36343. this._currentEffect.setTexture(name, texture);
  36344. };
  36345. /**
  36346. * Directly updates the value of the uniform in the cache AND on the GPU.
  36347. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36348. * @param {number[]|Float32Array} data Flattened data
  36349. */
  36350. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36351. this.updateUniform(uniformName, data, data.length);
  36352. this.update();
  36353. };
  36354. /**
  36355. * Binds this uniform buffer to an effect.
  36356. * @param {Effect} effect
  36357. * @param {string} name Name of the uniform block in the shader.
  36358. */
  36359. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36360. this._currentEffect = effect;
  36361. if (this._noUBO || !this._buffer) {
  36362. return;
  36363. }
  36364. effect.bindUniformBuffer(this._buffer, name);
  36365. };
  36366. /**
  36367. * Disposes the uniform buffer.
  36368. */
  36369. UniformBuffer.prototype.dispose = function () {
  36370. if (this._noUBO) {
  36371. return;
  36372. }
  36373. var index = this._engine._uniformBuffers.indexOf(this);
  36374. if (index !== -1) {
  36375. this._engine._uniformBuffers.splice(index, 1);
  36376. }
  36377. if (!this._buffer) {
  36378. return;
  36379. }
  36380. if (this._engine._releaseBuffer(this._buffer)) {
  36381. this._buffer = null;
  36382. }
  36383. };
  36384. // Pool for avoiding memory leaks
  36385. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36386. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36387. return UniformBuffer;
  36388. }());
  36389. BABYLON.UniformBuffer = UniformBuffer;
  36390. })(BABYLON || (BABYLON = {}));
  36391. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36392. var BABYLON;
  36393. (function (BABYLON) {
  36394. /**
  36395. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36396. */
  36397. var VertexData = /** @class */ (function () {
  36398. function VertexData() {
  36399. }
  36400. /**
  36401. * Uses the passed data array to set the set the values for the specified kind of data
  36402. * @param data a linear array of floating numbers
  36403. * @param kind the type of data that is being set, eg positions, colors etc
  36404. */
  36405. VertexData.prototype.set = function (data, kind) {
  36406. switch (kind) {
  36407. case BABYLON.VertexBuffer.PositionKind:
  36408. this.positions = data;
  36409. break;
  36410. case BABYLON.VertexBuffer.NormalKind:
  36411. this.normals = data;
  36412. break;
  36413. case BABYLON.VertexBuffer.TangentKind:
  36414. this.tangents = data;
  36415. break;
  36416. case BABYLON.VertexBuffer.UVKind:
  36417. this.uvs = data;
  36418. break;
  36419. case BABYLON.VertexBuffer.UV2Kind:
  36420. this.uvs2 = data;
  36421. break;
  36422. case BABYLON.VertexBuffer.UV3Kind:
  36423. this.uvs3 = data;
  36424. break;
  36425. case BABYLON.VertexBuffer.UV4Kind:
  36426. this.uvs4 = data;
  36427. break;
  36428. case BABYLON.VertexBuffer.UV5Kind:
  36429. this.uvs5 = data;
  36430. break;
  36431. case BABYLON.VertexBuffer.UV6Kind:
  36432. this.uvs6 = data;
  36433. break;
  36434. case BABYLON.VertexBuffer.ColorKind:
  36435. this.colors = data;
  36436. break;
  36437. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36438. this.matricesIndices = data;
  36439. break;
  36440. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36441. this.matricesWeights = data;
  36442. break;
  36443. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36444. this.matricesIndicesExtra = data;
  36445. break;
  36446. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36447. this.matricesWeightsExtra = data;
  36448. break;
  36449. }
  36450. };
  36451. /**
  36452. * Associates the vertexData to the passed Mesh.
  36453. * Sets it as updatable or not (default `false`)
  36454. * @param mesh the mesh the vertexData is applied to
  36455. * @param updatable when used and having the value true allows new data to update the vertexData
  36456. * @returns the VertexData
  36457. */
  36458. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36459. this._applyTo(mesh, updatable);
  36460. return this;
  36461. };
  36462. /**
  36463. * Associates the vertexData to the passed Geometry.
  36464. * Sets it as updatable or not (default `false`)
  36465. * @param geometry the geometry the vertexData is applied to
  36466. * @param updatable when used and having the value true allows new data to update the vertexData
  36467. * @returns VertexData
  36468. */
  36469. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36470. this._applyTo(geometry, updatable);
  36471. return this;
  36472. };
  36473. /**
  36474. * Updates the associated mesh
  36475. * @param mesh the mesh to be updated
  36476. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36477. * @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
  36478. * @returns VertexData
  36479. */
  36480. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36481. this._update(mesh);
  36482. return this;
  36483. };
  36484. /**
  36485. * Updates the associated geometry
  36486. * @param geometry the geometry to be updated
  36487. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36488. * @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
  36489. * @returns VertexData.
  36490. */
  36491. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36492. this._update(geometry);
  36493. return this;
  36494. };
  36495. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36496. if (updatable === void 0) { updatable = false; }
  36497. if (this.positions) {
  36498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36499. }
  36500. if (this.normals) {
  36501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36502. }
  36503. if (this.tangents) {
  36504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36505. }
  36506. if (this.uvs) {
  36507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36508. }
  36509. if (this.uvs2) {
  36510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36511. }
  36512. if (this.uvs3) {
  36513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36514. }
  36515. if (this.uvs4) {
  36516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36517. }
  36518. if (this.uvs5) {
  36519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36520. }
  36521. if (this.uvs6) {
  36522. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36523. }
  36524. if (this.colors) {
  36525. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36526. }
  36527. if (this.matricesIndices) {
  36528. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36529. }
  36530. if (this.matricesWeights) {
  36531. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36532. }
  36533. if (this.matricesIndicesExtra) {
  36534. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36535. }
  36536. if (this.matricesWeightsExtra) {
  36537. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36538. }
  36539. if (this.indices) {
  36540. meshOrGeometry.setIndices(this.indices, null, updatable);
  36541. }
  36542. else {
  36543. meshOrGeometry.setIndices([], null);
  36544. }
  36545. return this;
  36546. };
  36547. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36548. if (this.positions) {
  36549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36550. }
  36551. if (this.normals) {
  36552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36553. }
  36554. if (this.tangents) {
  36555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36556. }
  36557. if (this.uvs) {
  36558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36559. }
  36560. if (this.uvs2) {
  36561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36562. }
  36563. if (this.uvs3) {
  36564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36565. }
  36566. if (this.uvs4) {
  36567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36568. }
  36569. if (this.uvs5) {
  36570. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36571. }
  36572. if (this.uvs6) {
  36573. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36574. }
  36575. if (this.colors) {
  36576. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36577. }
  36578. if (this.matricesIndices) {
  36579. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36580. }
  36581. if (this.matricesWeights) {
  36582. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36583. }
  36584. if (this.matricesIndicesExtra) {
  36585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36586. }
  36587. if (this.matricesWeightsExtra) {
  36588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36589. }
  36590. if (this.indices) {
  36591. meshOrGeometry.setIndices(this.indices, null);
  36592. }
  36593. return this;
  36594. };
  36595. /**
  36596. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36597. * @param matrix the transforming matrix
  36598. * @returns the VertexData
  36599. */
  36600. VertexData.prototype.transform = function (matrix) {
  36601. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36602. var transformed = BABYLON.Vector3.Zero();
  36603. var index;
  36604. if (this.positions) {
  36605. var position = BABYLON.Vector3.Zero();
  36606. for (index = 0; index < this.positions.length; index += 3) {
  36607. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36608. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36609. this.positions[index] = transformed.x;
  36610. this.positions[index + 1] = transformed.y;
  36611. this.positions[index + 2] = transformed.z;
  36612. }
  36613. }
  36614. if (this.normals) {
  36615. var normal = BABYLON.Vector3.Zero();
  36616. for (index = 0; index < this.normals.length; index += 3) {
  36617. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36618. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36619. this.normals[index] = transformed.x;
  36620. this.normals[index + 1] = transformed.y;
  36621. this.normals[index + 2] = transformed.z;
  36622. }
  36623. }
  36624. if (this.tangents) {
  36625. var tangent = BABYLON.Vector4.Zero();
  36626. var tangentTransformed = BABYLON.Vector4.Zero();
  36627. for (index = 0; index < this.tangents.length; index += 4) {
  36628. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36629. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36630. this.tangents[index] = tangentTransformed.x;
  36631. this.tangents[index + 1] = tangentTransformed.y;
  36632. this.tangents[index + 2] = tangentTransformed.z;
  36633. this.tangents[index + 3] = tangentTransformed.w;
  36634. }
  36635. }
  36636. if (flip && this.indices) {
  36637. for (index = 0; index < this.indices.length; index += 3) {
  36638. var tmp = this.indices[index + 1];
  36639. this.indices[index + 1] = this.indices[index + 2];
  36640. this.indices[index + 2] = tmp;
  36641. }
  36642. }
  36643. return this;
  36644. };
  36645. /**
  36646. * Merges the passed VertexData into the current one
  36647. * @param other the VertexData to be merged into the current one
  36648. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36649. * @returns the modified VertexData
  36650. */
  36651. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36652. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36653. this._validate();
  36654. other._validate();
  36655. if (!this.normals !== !other.normals ||
  36656. !this.tangents !== !other.tangents ||
  36657. !this.uvs !== !other.uvs ||
  36658. !this.uvs2 !== !other.uvs2 ||
  36659. !this.uvs3 !== !other.uvs3 ||
  36660. !this.uvs4 !== !other.uvs4 ||
  36661. !this.uvs5 !== !other.uvs5 ||
  36662. !this.uvs6 !== !other.uvs6 ||
  36663. !this.colors !== !other.colors ||
  36664. !this.matricesIndices !== !other.matricesIndices ||
  36665. !this.matricesWeights !== !other.matricesWeights ||
  36666. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36667. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36668. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36669. }
  36670. if (other.indices) {
  36671. if (!this.indices) {
  36672. this.indices = [];
  36673. }
  36674. var offset = this.positions ? this.positions.length / 3 : 0;
  36675. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36676. if (isSrcTypedArray) {
  36677. var len = this.indices.length + other.indices.length;
  36678. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36679. temp.set(this.indices);
  36680. var decal = this.indices.length;
  36681. for (var index = 0; index < other.indices.length; index++) {
  36682. temp[decal + index] = other.indices[index] + offset;
  36683. }
  36684. this.indices = temp;
  36685. }
  36686. else {
  36687. for (var index = 0; index < other.indices.length; index++) {
  36688. this.indices.push(other.indices[index] + offset);
  36689. }
  36690. }
  36691. }
  36692. this.positions = this._mergeElement(this.positions, other.positions);
  36693. this.normals = this._mergeElement(this.normals, other.normals);
  36694. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36695. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36696. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36697. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36698. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36699. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36700. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36701. this.colors = this._mergeElement(this.colors, other.colors);
  36702. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36703. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36704. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36705. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36706. return this;
  36707. };
  36708. VertexData.prototype._mergeElement = function (source, other) {
  36709. if (!source) {
  36710. return other;
  36711. }
  36712. if (!other) {
  36713. return source;
  36714. }
  36715. var len = other.length + source.length;
  36716. var isSrcTypedArray = source instanceof Float32Array;
  36717. var isOthTypedArray = other instanceof Float32Array;
  36718. // use non-loop method when the source is Float32Array
  36719. if (isSrcTypedArray) {
  36720. var ret32 = new Float32Array(len);
  36721. ret32.set(source);
  36722. ret32.set(other, source.length);
  36723. return ret32;
  36724. // source is number[], when other is also use concat
  36725. }
  36726. else if (!isOthTypedArray) {
  36727. return source.concat(other);
  36728. // source is a number[], but other is a Float32Array, loop required
  36729. }
  36730. else {
  36731. var ret = source.slice(0); // copy source to a separate array
  36732. for (var i = 0, len = other.length; i < len; i++) {
  36733. ret.push(other[i]);
  36734. }
  36735. return ret;
  36736. }
  36737. };
  36738. VertexData.prototype._validate = function () {
  36739. if (!this.positions) {
  36740. throw new Error("Positions are required");
  36741. }
  36742. var getElementCount = function (kind, values) {
  36743. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36744. if ((values.length % stride) !== 0) {
  36745. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36746. }
  36747. return values.length / stride;
  36748. };
  36749. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36750. var validateElementCount = function (kind, values) {
  36751. var elementCount = getElementCount(kind, values);
  36752. if (elementCount !== positionsElementCount) {
  36753. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36754. }
  36755. };
  36756. if (this.normals)
  36757. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36758. if (this.tangents)
  36759. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36760. if (this.uvs)
  36761. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36762. if (this.uvs2)
  36763. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36764. if (this.uvs3)
  36765. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36766. if (this.uvs4)
  36767. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36768. if (this.uvs5)
  36769. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36770. if (this.uvs6)
  36771. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36772. if (this.colors)
  36773. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36774. if (this.matricesIndices)
  36775. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36776. if (this.matricesWeights)
  36777. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36778. if (this.matricesIndicesExtra)
  36779. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36780. if (this.matricesWeightsExtra)
  36781. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36782. };
  36783. /**
  36784. * Serializes the VertexData
  36785. * @returns a serialized object
  36786. */
  36787. VertexData.prototype.serialize = function () {
  36788. var serializationObject = this.serialize();
  36789. if (this.positions) {
  36790. serializationObject.positions = this.positions;
  36791. }
  36792. if (this.normals) {
  36793. serializationObject.normals = this.normals;
  36794. }
  36795. if (this.tangents) {
  36796. serializationObject.tangents = this.tangents;
  36797. }
  36798. if (this.uvs) {
  36799. serializationObject.uvs = this.uvs;
  36800. }
  36801. if (this.uvs2) {
  36802. serializationObject.uvs2 = this.uvs2;
  36803. }
  36804. if (this.uvs3) {
  36805. serializationObject.uvs3 = this.uvs3;
  36806. }
  36807. if (this.uvs4) {
  36808. serializationObject.uvs4 = this.uvs4;
  36809. }
  36810. if (this.uvs5) {
  36811. serializationObject.uvs5 = this.uvs5;
  36812. }
  36813. if (this.uvs6) {
  36814. serializationObject.uvs6 = this.uvs6;
  36815. }
  36816. if (this.colors) {
  36817. serializationObject.colors = this.colors;
  36818. }
  36819. if (this.matricesIndices) {
  36820. serializationObject.matricesIndices = this.matricesIndices;
  36821. serializationObject.matricesIndices._isExpanded = true;
  36822. }
  36823. if (this.matricesWeights) {
  36824. serializationObject.matricesWeights = this.matricesWeights;
  36825. }
  36826. if (this.matricesIndicesExtra) {
  36827. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36828. serializationObject.matricesIndicesExtra._isExpanded = true;
  36829. }
  36830. if (this.matricesWeightsExtra) {
  36831. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36832. }
  36833. serializationObject.indices = this.indices;
  36834. return serializationObject;
  36835. };
  36836. // Statics
  36837. /**
  36838. * Extracts the vertexData from a mesh
  36839. * @param mesh the mesh from which to extract the VertexData
  36840. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36841. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36842. * @returns the object VertexData associated to the passed mesh
  36843. */
  36844. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36845. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36846. };
  36847. /**
  36848. * Extracts the vertexData from the geometry
  36849. * @param geometry the geometry from which to extract the VertexData
  36850. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36851. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36852. * @returns the object VertexData associated to the passed mesh
  36853. */
  36854. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36855. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36856. };
  36857. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36858. var result = new VertexData();
  36859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36860. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36861. }
  36862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36863. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36864. }
  36865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36866. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36867. }
  36868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36869. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36870. }
  36871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36872. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36873. }
  36874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36875. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36876. }
  36877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36878. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36879. }
  36880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36881. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36882. }
  36883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36884. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36885. }
  36886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36887. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36888. }
  36889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36890. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36891. }
  36892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36893. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36894. }
  36895. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36896. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36897. }
  36898. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36899. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36900. }
  36901. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36902. return result;
  36903. };
  36904. /**
  36905. * Creates the VertexData for a Ribbon
  36906. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36907. * * pathArray array of paths, each of which an array of successive Vector3
  36908. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36909. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36910. * * 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
  36911. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36912. * * 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)
  36913. * * 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)
  36914. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36915. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36916. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36917. * @returns the VertexData of the ribbon
  36918. */
  36919. VertexData.CreateRibbon = function (options) {
  36920. var pathArray = options.pathArray;
  36921. var closeArray = options.closeArray || false;
  36922. var closePath = options.closePath || false;
  36923. var invertUV = options.invertUV || false;
  36924. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36925. var offset = options.offset || defaultOffset;
  36926. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36927. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36928. var customUV = options.uvs;
  36929. var customColors = options.colors;
  36930. var positions = [];
  36931. var indices = [];
  36932. var normals = [];
  36933. var uvs = [];
  36934. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36935. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36936. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36937. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36938. var minlg; // minimal length among all paths from pathArray
  36939. var lg = []; // array of path lengths : nb of vertex per path
  36940. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36941. var p; // path iterator
  36942. var i; // point iterator
  36943. var j; // point iterator
  36944. // if single path in pathArray
  36945. if (pathArray.length < 2) {
  36946. var ar1 = [];
  36947. var ar2 = [];
  36948. for (i = 0; i < pathArray[0].length - offset; i++) {
  36949. ar1.push(pathArray[0][i]);
  36950. ar2.push(pathArray[0][i + offset]);
  36951. }
  36952. pathArray = [ar1, ar2];
  36953. }
  36954. // positions and horizontal distances (u)
  36955. var idc = 0;
  36956. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36957. var path;
  36958. var l;
  36959. minlg = pathArray[0].length;
  36960. var vectlg;
  36961. var dist;
  36962. for (p = 0; p < pathArray.length; p++) {
  36963. uTotalDistance[p] = 0;
  36964. us[p] = [0];
  36965. path = pathArray[p];
  36966. l = path.length;
  36967. minlg = (minlg < l) ? minlg : l;
  36968. j = 0;
  36969. while (j < l) {
  36970. positions.push(path[j].x, path[j].y, path[j].z);
  36971. if (j > 0) {
  36972. vectlg = path[j].subtract(path[j - 1]).length();
  36973. dist = vectlg + uTotalDistance[p];
  36974. us[p].push(dist);
  36975. uTotalDistance[p] = dist;
  36976. }
  36977. j++;
  36978. }
  36979. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36980. j--;
  36981. positions.push(path[0].x, path[0].y, path[0].z);
  36982. vectlg = path[j].subtract(path[0]).length();
  36983. dist = vectlg + uTotalDistance[p];
  36984. us[p].push(dist);
  36985. uTotalDistance[p] = dist;
  36986. }
  36987. lg[p] = l + closePathCorr;
  36988. idx[p] = idc;
  36989. idc += (l + closePathCorr);
  36990. }
  36991. // vertical distances (v)
  36992. var path1;
  36993. var path2;
  36994. var vertex1 = null;
  36995. var vertex2 = null;
  36996. for (i = 0; i < minlg + closePathCorr; i++) {
  36997. vTotalDistance[i] = 0;
  36998. vs[i] = [0];
  36999. for (p = 0; p < pathArray.length - 1; p++) {
  37000. path1 = pathArray[p];
  37001. path2 = pathArray[p + 1];
  37002. if (i === minlg) { // closePath
  37003. vertex1 = path1[0];
  37004. vertex2 = path2[0];
  37005. }
  37006. else {
  37007. vertex1 = path1[i];
  37008. vertex2 = path2[i];
  37009. }
  37010. vectlg = vertex2.subtract(vertex1).length();
  37011. dist = vectlg + vTotalDistance[i];
  37012. vs[i].push(dist);
  37013. vTotalDistance[i] = dist;
  37014. }
  37015. if (closeArray && vertex2 && vertex1) {
  37016. path1 = pathArray[p];
  37017. path2 = pathArray[0];
  37018. if (i === minlg) { // closePath
  37019. vertex2 = path2[0];
  37020. }
  37021. vectlg = vertex2.subtract(vertex1).length();
  37022. dist = vectlg + vTotalDistance[i];
  37023. vTotalDistance[i] = dist;
  37024. }
  37025. }
  37026. // uvs
  37027. var u;
  37028. var v;
  37029. if (customUV) {
  37030. for (p = 0; p < customUV.length; p++) {
  37031. uvs.push(customUV[p].x, customUV[p].y);
  37032. }
  37033. }
  37034. else {
  37035. for (p = 0; p < pathArray.length; p++) {
  37036. for (i = 0; i < minlg + closePathCorr; i++) {
  37037. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37038. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37039. if (invertUV) {
  37040. uvs.push(v, u);
  37041. }
  37042. else {
  37043. uvs.push(u, v);
  37044. }
  37045. }
  37046. }
  37047. }
  37048. // indices
  37049. p = 0; // path index
  37050. var pi = 0; // positions array index
  37051. var l1 = lg[p] - 1; // path1 length
  37052. var l2 = lg[p + 1] - 1; // path2 length
  37053. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37054. var shft = idx[1] - idx[0]; // shift
  37055. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37056. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37057. // 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
  37058. indices.push(pi, pi + shft, pi + 1);
  37059. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37060. pi += 1;
  37061. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37062. p++;
  37063. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37064. shft = idx[0] - idx[p];
  37065. l1 = lg[p] - 1;
  37066. l2 = lg[0] - 1;
  37067. }
  37068. else {
  37069. shft = idx[p + 1] - idx[p];
  37070. l1 = lg[p] - 1;
  37071. l2 = lg[p + 1] - 1;
  37072. }
  37073. pi = idx[p];
  37074. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37075. }
  37076. }
  37077. // normals
  37078. VertexData.ComputeNormals(positions, indices, normals);
  37079. if (closePath) { // update both the first and last vertex normals to their average value
  37080. var indexFirst = 0;
  37081. var indexLast = 0;
  37082. for (p = 0; p < pathArray.length; p++) {
  37083. indexFirst = idx[p] * 3;
  37084. if (p + 1 < pathArray.length) {
  37085. indexLast = (idx[p + 1] - 1) * 3;
  37086. }
  37087. else {
  37088. indexLast = normals.length - 3;
  37089. }
  37090. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37091. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37092. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37093. normals[indexLast] = normals[indexFirst];
  37094. normals[indexLast + 1] = normals[indexFirst + 1];
  37095. normals[indexLast + 2] = normals[indexFirst + 2];
  37096. }
  37097. }
  37098. // sides
  37099. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37100. // Colors
  37101. var colors = null;
  37102. if (customColors) {
  37103. colors = new Float32Array(customColors.length * 4);
  37104. for (var c = 0; c < customColors.length; c++) {
  37105. colors[c * 4] = customColors[c].r;
  37106. colors[c * 4 + 1] = customColors[c].g;
  37107. colors[c * 4 + 2] = customColors[c].b;
  37108. colors[c * 4 + 3] = customColors[c].a;
  37109. }
  37110. }
  37111. // Result
  37112. var vertexData = new VertexData();
  37113. var positions32 = new Float32Array(positions);
  37114. var normals32 = new Float32Array(normals);
  37115. var uvs32 = new Float32Array(uvs);
  37116. vertexData.indices = indices;
  37117. vertexData.positions = positions32;
  37118. vertexData.normals = normals32;
  37119. vertexData.uvs = uvs32;
  37120. if (colors) {
  37121. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37122. }
  37123. if (closePath) {
  37124. vertexData._idx = idx;
  37125. }
  37126. return vertexData;
  37127. };
  37128. /**
  37129. * Creates the VertexData for a box
  37130. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37131. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37132. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37133. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37134. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37135. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37136. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37137. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37138. * * 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)
  37139. * * 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)
  37140. * @returns the VertexData of the box
  37141. */
  37142. VertexData.CreateBox = function (options) {
  37143. var normalsSource = [
  37144. new BABYLON.Vector3(0, 0, 1),
  37145. new BABYLON.Vector3(0, 0, -1),
  37146. new BABYLON.Vector3(1, 0, 0),
  37147. new BABYLON.Vector3(-1, 0, 0),
  37148. new BABYLON.Vector3(0, 1, 0),
  37149. new BABYLON.Vector3(0, -1, 0)
  37150. ];
  37151. var indices = [];
  37152. var positions = [];
  37153. var normals = [];
  37154. var uvs = [];
  37155. var width = options.width || options.size || 1;
  37156. var height = options.height || options.size || 1;
  37157. var depth = options.depth || options.size || 1;
  37158. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37159. var faceUV = options.faceUV || new Array(6);
  37160. var faceColors = options.faceColors;
  37161. var colors = [];
  37162. // default face colors and UV if undefined
  37163. for (var f = 0; f < 6; f++) {
  37164. if (faceUV[f] === undefined) {
  37165. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37166. }
  37167. if (faceColors && faceColors[f] === undefined) {
  37168. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37169. }
  37170. }
  37171. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37172. // Create each face in turn.
  37173. for (var index = 0; index < normalsSource.length; index++) {
  37174. var normal = normalsSource[index];
  37175. // Get two vectors perpendicular to the face normal and to each other.
  37176. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37177. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37178. // Six indices (two triangles) per face.
  37179. var verticesLength = positions.length / 3;
  37180. indices.push(verticesLength);
  37181. indices.push(verticesLength + 1);
  37182. indices.push(verticesLength + 2);
  37183. indices.push(verticesLength);
  37184. indices.push(verticesLength + 2);
  37185. indices.push(verticesLength + 3);
  37186. // Four vertices per face.
  37187. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37188. positions.push(vertex.x, vertex.y, vertex.z);
  37189. normals.push(normal.x, normal.y, normal.z);
  37190. uvs.push(faceUV[index].z, faceUV[index].w);
  37191. if (faceColors) {
  37192. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37193. }
  37194. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37195. positions.push(vertex.x, vertex.y, vertex.z);
  37196. normals.push(normal.x, normal.y, normal.z);
  37197. uvs.push(faceUV[index].x, faceUV[index].w);
  37198. if (faceColors) {
  37199. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37200. }
  37201. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37202. positions.push(vertex.x, vertex.y, vertex.z);
  37203. normals.push(normal.x, normal.y, normal.z);
  37204. uvs.push(faceUV[index].x, faceUV[index].y);
  37205. if (faceColors) {
  37206. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37207. }
  37208. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37209. positions.push(vertex.x, vertex.y, vertex.z);
  37210. normals.push(normal.x, normal.y, normal.z);
  37211. uvs.push(faceUV[index].z, faceUV[index].y);
  37212. if (faceColors) {
  37213. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37214. }
  37215. }
  37216. // sides
  37217. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37218. // Result
  37219. var vertexData = new VertexData();
  37220. vertexData.indices = indices;
  37221. vertexData.positions = positions;
  37222. vertexData.normals = normals;
  37223. vertexData.uvs = uvs;
  37224. if (faceColors) {
  37225. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37226. vertexData.colors = totalColors;
  37227. }
  37228. return vertexData;
  37229. };
  37230. /**
  37231. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37232. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37233. * * segments sets the number of horizontal strips optional, default 32
  37234. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37235. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37236. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37237. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37238. * * 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
  37239. * * 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
  37240. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37241. * * 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)
  37242. * * 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)
  37243. * @returns the VertexData of the ellipsoid
  37244. */
  37245. VertexData.CreateSphere = function (options) {
  37246. var segments = options.segments || 32;
  37247. var diameterX = options.diameterX || options.diameter || 1;
  37248. var diameterY = options.diameterY || options.diameter || 1;
  37249. var diameterZ = options.diameterZ || options.diameter || 1;
  37250. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37251. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37252. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37253. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37254. var totalZRotationSteps = 2 + segments;
  37255. var totalYRotationSteps = 2 * totalZRotationSteps;
  37256. var indices = [];
  37257. var positions = [];
  37258. var normals = [];
  37259. var uvs = [];
  37260. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37261. var normalizedZ = zRotationStep / totalZRotationSteps;
  37262. var angleZ = normalizedZ * Math.PI * slice;
  37263. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37264. var normalizedY = yRotationStep / totalYRotationSteps;
  37265. var angleY = normalizedY * Math.PI * 2 * arc;
  37266. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37267. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37268. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37269. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37270. var vertex = complete.multiply(radius);
  37271. var normal = complete.divide(radius).normalize();
  37272. positions.push(vertex.x, vertex.y, vertex.z);
  37273. normals.push(normal.x, normal.y, normal.z);
  37274. uvs.push(normalizedY, normalizedZ);
  37275. }
  37276. if (zRotationStep > 0) {
  37277. var verticesCount = positions.length / 3;
  37278. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37279. indices.push((firstIndex));
  37280. indices.push((firstIndex + 1));
  37281. indices.push(firstIndex + totalYRotationSteps + 1);
  37282. indices.push((firstIndex + totalYRotationSteps + 1));
  37283. indices.push((firstIndex + 1));
  37284. indices.push((firstIndex + totalYRotationSteps + 2));
  37285. }
  37286. }
  37287. }
  37288. // Sides
  37289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37290. // Result
  37291. var vertexData = new VertexData();
  37292. vertexData.indices = indices;
  37293. vertexData.positions = positions;
  37294. vertexData.normals = normals;
  37295. vertexData.uvs = uvs;
  37296. return vertexData;
  37297. };
  37298. /**
  37299. * Creates the VertexData for a cylinder, cone or prism
  37300. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37301. * * height sets the height (y direction) of the cylinder, optional, default 2
  37302. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37303. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37304. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37305. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37306. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37307. * * 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
  37308. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37309. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37310. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37311. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37312. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37313. * * 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)
  37314. * * 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)
  37315. * @returns the VertexData of the cylinder, cone or prism
  37316. */
  37317. VertexData.CreateCylinder = function (options) {
  37318. var height = options.height || 2;
  37319. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37320. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37321. var tessellation = options.tessellation || 24;
  37322. var subdivisions = options.subdivisions || 1;
  37323. var hasRings = options.hasRings ? true : false;
  37324. var enclose = options.enclose ? true : false;
  37325. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37327. var faceUV = options.faceUV || new Array(3);
  37328. var faceColors = options.faceColors;
  37329. // default face colors and UV if undefined
  37330. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37331. var ringNb = (hasRings) ? subdivisions : 1;
  37332. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37333. var f;
  37334. for (f = 0; f < surfaceNb; f++) {
  37335. if (faceColors && faceColors[f] === undefined) {
  37336. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37337. }
  37338. }
  37339. for (f = 0; f < surfaceNb; f++) {
  37340. if (faceUV && faceUV[f] === undefined) {
  37341. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37342. }
  37343. }
  37344. var indices = new Array();
  37345. var positions = new Array();
  37346. var normals = new Array();
  37347. var uvs = new Array();
  37348. var colors = new Array();
  37349. var angle_step = Math.PI * 2 * arc / tessellation;
  37350. var angle;
  37351. var h;
  37352. var radius;
  37353. var tan = (diameterBottom - diameterTop) / 2 / height;
  37354. var ringVertex = BABYLON.Vector3.Zero();
  37355. var ringNormal = BABYLON.Vector3.Zero();
  37356. var ringFirstVertex = BABYLON.Vector3.Zero();
  37357. var ringFirstNormal = BABYLON.Vector3.Zero();
  37358. var quadNormal = BABYLON.Vector3.Zero();
  37359. var Y = BABYLON.Axis.Y;
  37360. // positions, normals, uvs
  37361. var i;
  37362. var j;
  37363. var r;
  37364. var ringIdx = 1;
  37365. var s = 1; // surface index
  37366. var cs = 0;
  37367. var v = 0;
  37368. for (i = 0; i <= subdivisions; i++) {
  37369. h = i / subdivisions;
  37370. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37371. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37372. for (r = 0; r < ringIdx; r++) {
  37373. if (hasRings) {
  37374. s += r;
  37375. }
  37376. if (enclose) {
  37377. s += 2 * r;
  37378. }
  37379. for (j = 0; j <= tessellation; j++) {
  37380. angle = j * angle_step;
  37381. // position
  37382. ringVertex.x = Math.cos(-angle) * radius;
  37383. ringVertex.y = -height / 2 + h * height;
  37384. ringVertex.z = Math.sin(-angle) * radius;
  37385. // normal
  37386. if (diameterTop === 0 && i === subdivisions) {
  37387. // if no top cap, reuse former normals
  37388. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37389. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37390. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37391. }
  37392. else {
  37393. ringNormal.x = ringVertex.x;
  37394. ringNormal.z = ringVertex.z;
  37395. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37396. ringNormal.normalize();
  37397. }
  37398. // keep first ring vertex values for enclose
  37399. if (j === 0) {
  37400. ringFirstVertex.copyFrom(ringVertex);
  37401. ringFirstNormal.copyFrom(ringNormal);
  37402. }
  37403. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37404. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37405. if (hasRings) {
  37406. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37407. }
  37408. else {
  37409. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37410. }
  37411. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37412. if (faceColors) {
  37413. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37414. }
  37415. }
  37416. // if enclose, add four vertices and their dedicated normals
  37417. if (arc !== 1 && enclose) {
  37418. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37419. positions.push(0, ringVertex.y, 0);
  37420. positions.push(0, ringVertex.y, 0);
  37421. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37422. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37423. quadNormal.normalize();
  37424. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37425. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37426. quadNormal.normalize();
  37427. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37428. if (hasRings) {
  37429. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37430. }
  37431. else {
  37432. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37433. }
  37434. uvs.push(faceUV[s + 1].x, v);
  37435. uvs.push(faceUV[s + 1].z, v);
  37436. if (hasRings) {
  37437. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37438. }
  37439. else {
  37440. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37441. }
  37442. uvs.push(faceUV[s + 2].x, v);
  37443. uvs.push(faceUV[s + 2].z, v);
  37444. if (faceColors) {
  37445. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37446. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37447. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37448. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37449. }
  37450. }
  37451. if (cs !== s) {
  37452. cs = s;
  37453. }
  37454. }
  37455. }
  37456. // indices
  37457. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37458. var s;
  37459. i = 0;
  37460. for (s = 0; s < subdivisions; s++) {
  37461. var i0 = 0;
  37462. var i1 = 0;
  37463. var i2 = 0;
  37464. var i3 = 0;
  37465. for (j = 0; j < tessellation; j++) {
  37466. i0 = i * (e + 1) + j;
  37467. i1 = (i + 1) * (e + 1) + j;
  37468. i2 = i * (e + 1) + (j + 1);
  37469. i3 = (i + 1) * (e + 1) + (j + 1);
  37470. indices.push(i0, i1, i2);
  37471. indices.push(i3, i2, i1);
  37472. }
  37473. if (arc !== 1 && enclose) { // if enclose, add two quads
  37474. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37475. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37476. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37477. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37478. }
  37479. i = (hasRings) ? (i + 2) : (i + 1);
  37480. }
  37481. // Caps
  37482. var createCylinderCap = function (isTop) {
  37483. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37484. if (radius === 0) {
  37485. return;
  37486. }
  37487. // Cap positions, normals & uvs
  37488. var angle;
  37489. var circleVector;
  37490. var i;
  37491. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37492. var c = null;
  37493. if (faceColors) {
  37494. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37495. }
  37496. // cap center
  37497. var vbase = positions.length / 3;
  37498. var offset = isTop ? height / 2 : -height / 2;
  37499. var center = new BABYLON.Vector3(0, offset, 0);
  37500. positions.push(center.x, center.y, center.z);
  37501. normals.push(0, isTop ? 1 : -1, 0);
  37502. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37503. if (c) {
  37504. colors.push(c.r, c.g, c.b, c.a);
  37505. }
  37506. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37507. for (i = 0; i <= tessellation; i++) {
  37508. angle = Math.PI * 2 * i * arc / tessellation;
  37509. var cos = Math.cos(-angle);
  37510. var sin = Math.sin(-angle);
  37511. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37512. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37513. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37514. normals.push(0, isTop ? 1 : -1, 0);
  37515. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37516. if (c) {
  37517. colors.push(c.r, c.g, c.b, c.a);
  37518. }
  37519. }
  37520. // Cap indices
  37521. for (i = 0; i < tessellation; i++) {
  37522. if (!isTop) {
  37523. indices.push(vbase);
  37524. indices.push(vbase + (i + 1));
  37525. indices.push(vbase + (i + 2));
  37526. }
  37527. else {
  37528. indices.push(vbase);
  37529. indices.push(vbase + (i + 2));
  37530. indices.push(vbase + (i + 1));
  37531. }
  37532. }
  37533. };
  37534. // add caps to geometry
  37535. createCylinderCap(false);
  37536. createCylinderCap(true);
  37537. // Sides
  37538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37539. var vertexData = new VertexData();
  37540. vertexData.indices = indices;
  37541. vertexData.positions = positions;
  37542. vertexData.normals = normals;
  37543. vertexData.uvs = uvs;
  37544. if (faceColors) {
  37545. vertexData.colors = colors;
  37546. }
  37547. return vertexData;
  37548. };
  37549. /**
  37550. * Creates the VertexData for a torus
  37551. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37552. * * diameter the diameter of the torus, optional default 1
  37553. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37554. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37555. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37556. * * 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)
  37557. * * 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)
  37558. * @returns the VertexData of the torus
  37559. */
  37560. VertexData.CreateTorus = function (options) {
  37561. var indices = [];
  37562. var positions = [];
  37563. var normals = [];
  37564. var uvs = [];
  37565. var diameter = options.diameter || 1;
  37566. var thickness = options.thickness || 0.5;
  37567. var tessellation = options.tessellation || 16;
  37568. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37569. var stride = tessellation + 1;
  37570. for (var i = 0; i <= tessellation; i++) {
  37571. var u = i / tessellation;
  37572. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37573. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37574. for (var j = 0; j <= tessellation; j++) {
  37575. var v = 1 - j / tessellation;
  37576. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37577. var dx = Math.cos(innerAngle);
  37578. var dy = Math.sin(innerAngle);
  37579. // Create a vertex.
  37580. var normal = new BABYLON.Vector3(dx, dy, 0);
  37581. var position = normal.scale(thickness / 2);
  37582. var textureCoordinate = new BABYLON.Vector2(u, v);
  37583. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37584. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37585. positions.push(position.x, position.y, position.z);
  37586. normals.push(normal.x, normal.y, normal.z);
  37587. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37588. // And create indices for two triangles.
  37589. var nextI = (i + 1) % stride;
  37590. var nextJ = (j + 1) % stride;
  37591. indices.push(i * stride + j);
  37592. indices.push(i * stride + nextJ);
  37593. indices.push(nextI * stride + j);
  37594. indices.push(i * stride + nextJ);
  37595. indices.push(nextI * stride + nextJ);
  37596. indices.push(nextI * stride + j);
  37597. }
  37598. }
  37599. // Sides
  37600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37601. // Result
  37602. var vertexData = new VertexData();
  37603. vertexData.indices = indices;
  37604. vertexData.positions = positions;
  37605. vertexData.normals = normals;
  37606. vertexData.uvs = uvs;
  37607. return vertexData;
  37608. };
  37609. /**
  37610. * Creates the VertexData of the LineSystem
  37611. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37612. * - lines an array of lines, each line being an array of successive Vector3
  37613. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37614. * @returns the VertexData of the LineSystem
  37615. */
  37616. VertexData.CreateLineSystem = function (options) {
  37617. var indices = [];
  37618. var positions = [];
  37619. var lines = options.lines;
  37620. var colors = options.colors;
  37621. var vertexColors = [];
  37622. var idx = 0;
  37623. for (var l = 0; l < lines.length; l++) {
  37624. var points = lines[l];
  37625. for (var index = 0; index < points.length; index++) {
  37626. positions.push(points[index].x, points[index].y, points[index].z);
  37627. if (colors) {
  37628. var color = colors[l];
  37629. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37630. }
  37631. if (index > 0) {
  37632. indices.push(idx - 1);
  37633. indices.push(idx);
  37634. }
  37635. idx++;
  37636. }
  37637. }
  37638. var vertexData = new VertexData();
  37639. vertexData.indices = indices;
  37640. vertexData.positions = positions;
  37641. if (colors) {
  37642. vertexData.colors = vertexColors;
  37643. }
  37644. return vertexData;
  37645. };
  37646. /**
  37647. * Create the VertexData for a DashedLines
  37648. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37649. * - points an array successive Vector3
  37650. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37651. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37652. * - dashNb the intended total number of dashes, optional, default 200
  37653. * @returns the VertexData for the DashedLines
  37654. */
  37655. VertexData.CreateDashedLines = function (options) {
  37656. var dashSize = options.dashSize || 3;
  37657. var gapSize = options.gapSize || 1;
  37658. var dashNb = options.dashNb || 200;
  37659. var points = options.points;
  37660. var positions = new Array();
  37661. var indices = new Array();
  37662. var curvect = BABYLON.Vector3.Zero();
  37663. var lg = 0;
  37664. var nb = 0;
  37665. var shft = 0;
  37666. var dashshft = 0;
  37667. var curshft = 0;
  37668. var idx = 0;
  37669. var i = 0;
  37670. for (i = 0; i < points.length - 1; i++) {
  37671. points[i + 1].subtractToRef(points[i], curvect);
  37672. lg += curvect.length();
  37673. }
  37674. shft = lg / dashNb;
  37675. dashshft = dashSize * shft / (dashSize + gapSize);
  37676. for (i = 0; i < points.length - 1; i++) {
  37677. points[i + 1].subtractToRef(points[i], curvect);
  37678. nb = Math.floor(curvect.length() / shft);
  37679. curvect.normalize();
  37680. for (var j = 0; j < nb; j++) {
  37681. curshft = shft * j;
  37682. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37683. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37684. indices.push(idx, idx + 1);
  37685. idx += 2;
  37686. }
  37687. }
  37688. // Result
  37689. var vertexData = new VertexData();
  37690. vertexData.positions = positions;
  37691. vertexData.indices = indices;
  37692. return vertexData;
  37693. };
  37694. /**
  37695. * Creates the VertexData for a Ground
  37696. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37697. * - width the width (x direction) of the ground, optional, default 1
  37698. * - height the height (z direction) of the ground, optional, default 1
  37699. * - subdivisions the number of subdivisions per side, optional, default 1
  37700. * @returns the VertexData of the Ground
  37701. */
  37702. VertexData.CreateGround = function (options) {
  37703. var indices = [];
  37704. var positions = [];
  37705. var normals = [];
  37706. var uvs = [];
  37707. var row, col;
  37708. var width = options.width || 1;
  37709. var height = options.height || 1;
  37710. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37711. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37712. for (row = 0; row <= subdivisionsY; row++) {
  37713. for (col = 0; col <= subdivisionsX; col++) {
  37714. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37715. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37716. positions.push(position.x, position.y, position.z);
  37717. normals.push(normal.x, normal.y, normal.z);
  37718. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37719. }
  37720. }
  37721. for (row = 0; row < subdivisionsY; row++) {
  37722. for (col = 0; col < subdivisionsX; col++) {
  37723. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37724. indices.push(col + 1 + row * (subdivisionsX + 1));
  37725. indices.push(col + row * (subdivisionsX + 1));
  37726. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37727. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37728. indices.push(col + row * (subdivisionsX + 1));
  37729. }
  37730. }
  37731. // Result
  37732. var vertexData = new VertexData();
  37733. vertexData.indices = indices;
  37734. vertexData.positions = positions;
  37735. vertexData.normals = normals;
  37736. vertexData.uvs = uvs;
  37737. return vertexData;
  37738. };
  37739. /**
  37740. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37741. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37742. * * xmin the ground minimum X coordinate, optional, default -1
  37743. * * zmin the ground minimum Z coordinate, optional, default -1
  37744. * * xmax the ground maximum X coordinate, optional, default 1
  37745. * * zmax the ground maximum Z coordinate, optional, default 1
  37746. * * 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}
  37747. * * 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}
  37748. * @returns the VertexData of the TiledGround
  37749. */
  37750. VertexData.CreateTiledGround = function (options) {
  37751. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37752. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37753. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37754. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37755. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37756. var precision = options.precision || { w: 1, h: 1 };
  37757. var indices = new Array();
  37758. var positions = new Array();
  37759. var normals = new Array();
  37760. var uvs = new Array();
  37761. var row, col, tileRow, tileCol;
  37762. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37763. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37764. precision.w = (precision.w < 1) ? 1 : precision.w;
  37765. precision.h = (precision.h < 1) ? 1 : precision.h;
  37766. var tileSize = {
  37767. 'w': (xmax - xmin) / subdivisions.w,
  37768. 'h': (zmax - zmin) / subdivisions.h
  37769. };
  37770. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37771. // Indices
  37772. var base = positions.length / 3;
  37773. var rowLength = precision.w + 1;
  37774. for (row = 0; row < precision.h; row++) {
  37775. for (col = 0; col < precision.w; col++) {
  37776. var square = [
  37777. base + col + row * rowLength,
  37778. base + (col + 1) + row * rowLength,
  37779. base + (col + 1) + (row + 1) * rowLength,
  37780. base + col + (row + 1) * rowLength
  37781. ];
  37782. indices.push(square[1]);
  37783. indices.push(square[2]);
  37784. indices.push(square[3]);
  37785. indices.push(square[0]);
  37786. indices.push(square[1]);
  37787. indices.push(square[3]);
  37788. }
  37789. }
  37790. // Position, normals and uvs
  37791. var position = BABYLON.Vector3.Zero();
  37792. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37793. for (row = 0; row <= precision.h; row++) {
  37794. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37795. for (col = 0; col <= precision.w; col++) {
  37796. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37797. position.y = 0;
  37798. positions.push(position.x, position.y, position.z);
  37799. normals.push(normal.x, normal.y, normal.z);
  37800. uvs.push(col / precision.w, row / precision.h);
  37801. }
  37802. }
  37803. }
  37804. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37805. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37806. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37807. }
  37808. }
  37809. // Result
  37810. var vertexData = new VertexData();
  37811. vertexData.indices = indices;
  37812. vertexData.positions = positions;
  37813. vertexData.normals = normals;
  37814. vertexData.uvs = uvs;
  37815. return vertexData;
  37816. };
  37817. /**
  37818. * Creates the VertexData of the Ground designed from a heightmap
  37819. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37820. * * width the width (x direction) of the ground
  37821. * * height the height (z direction) of the ground
  37822. * * subdivisions the number of subdivisions per side
  37823. * * minHeight the minimum altitude on the ground, optional, default 0
  37824. * * maxHeight the maximum altitude on the ground, optional default 1
  37825. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37826. * * buffer the array holding the image color data
  37827. * * bufferWidth the width of image
  37828. * * bufferHeight the height of image
  37829. * @returns the VertexData of the Ground designed from a heightmap
  37830. */
  37831. VertexData.CreateGroundFromHeightMap = function (options) {
  37832. var indices = [];
  37833. var positions = [];
  37834. var normals = [];
  37835. var uvs = [];
  37836. var row, col;
  37837. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37838. // Vertices
  37839. for (row = 0; row <= options.subdivisions; row++) {
  37840. for (col = 0; col <= options.subdivisions; col++) {
  37841. 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));
  37842. // Compute height
  37843. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37844. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37845. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37846. var r = options.buffer[pos] / 255.0;
  37847. var g = options.buffer[pos + 1] / 255.0;
  37848. var b = options.buffer[pos + 2] / 255.0;
  37849. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37850. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37851. // Add vertex
  37852. positions.push(position.x, position.y, position.z);
  37853. normals.push(0, 0, 0);
  37854. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37855. }
  37856. }
  37857. // Indices
  37858. for (row = 0; row < options.subdivisions; row++) {
  37859. for (col = 0; col < options.subdivisions; col++) {
  37860. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37861. indices.push(col + 1 + row * (options.subdivisions + 1));
  37862. indices.push(col + row * (options.subdivisions + 1));
  37863. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37864. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37865. indices.push(col + row * (options.subdivisions + 1));
  37866. }
  37867. }
  37868. // Normals
  37869. VertexData.ComputeNormals(positions, indices, normals);
  37870. // Result
  37871. var vertexData = new VertexData();
  37872. vertexData.indices = indices;
  37873. vertexData.positions = positions;
  37874. vertexData.normals = normals;
  37875. vertexData.uvs = uvs;
  37876. return vertexData;
  37877. };
  37878. /**
  37879. * Creates the VertexData for a Plane
  37880. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37881. * * size sets the width and height of the plane to the value of size, optional default 1
  37882. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37883. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37884. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37885. * * 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)
  37886. * * 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)
  37887. * @returns the VertexData of the box
  37888. */
  37889. VertexData.CreatePlane = function (options) {
  37890. var indices = [];
  37891. var positions = [];
  37892. var normals = [];
  37893. var uvs = [];
  37894. var width = options.width || options.size || 1;
  37895. var height = options.height || options.size || 1;
  37896. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37897. // Vertices
  37898. var halfWidth = width / 2.0;
  37899. var halfHeight = height / 2.0;
  37900. positions.push(-halfWidth, -halfHeight, 0);
  37901. normals.push(0, 0, -1.0);
  37902. uvs.push(0.0, 0.0);
  37903. positions.push(halfWidth, -halfHeight, 0);
  37904. normals.push(0, 0, -1.0);
  37905. uvs.push(1.0, 0.0);
  37906. positions.push(halfWidth, halfHeight, 0);
  37907. normals.push(0, 0, -1.0);
  37908. uvs.push(1.0, 1.0);
  37909. positions.push(-halfWidth, halfHeight, 0);
  37910. normals.push(0, 0, -1.0);
  37911. uvs.push(0.0, 1.0);
  37912. // Indices
  37913. indices.push(0);
  37914. indices.push(1);
  37915. indices.push(2);
  37916. indices.push(0);
  37917. indices.push(2);
  37918. indices.push(3);
  37919. // Sides
  37920. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37921. // Result
  37922. var vertexData = new VertexData();
  37923. vertexData.indices = indices;
  37924. vertexData.positions = positions;
  37925. vertexData.normals = normals;
  37926. vertexData.uvs = uvs;
  37927. return vertexData;
  37928. };
  37929. /**
  37930. * Creates the VertexData of the Disc or regular Polygon
  37931. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37932. * * radius the radius of the disc, optional default 0.5
  37933. * * tessellation the number of polygon sides, optional, default 64
  37934. * * 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
  37935. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37936. * * 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)
  37937. * * 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)
  37938. * @returns the VertexData of the box
  37939. */
  37940. VertexData.CreateDisc = function (options) {
  37941. var positions = new Array();
  37942. var indices = new Array();
  37943. var normals = new Array();
  37944. var uvs = new Array();
  37945. var radius = options.radius || 0.5;
  37946. var tessellation = options.tessellation || 64;
  37947. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37948. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37949. // positions and uvs
  37950. positions.push(0, 0, 0); // disc center first
  37951. uvs.push(0.5, 0.5);
  37952. var theta = Math.PI * 2 * arc;
  37953. var step = theta / tessellation;
  37954. for (var a = 0; a < theta; a += step) {
  37955. var x = Math.cos(a);
  37956. var y = Math.sin(a);
  37957. var u = (x + 1) / 2;
  37958. var v = (1 - y) / 2;
  37959. positions.push(radius * x, radius * y, 0);
  37960. uvs.push(u, v);
  37961. }
  37962. if (arc === 1) {
  37963. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37964. uvs.push(uvs[2], uvs[3]);
  37965. }
  37966. //indices
  37967. var vertexNb = positions.length / 3;
  37968. for (var i = 1; i < vertexNb - 1; i++) {
  37969. indices.push(i + 1, 0, i);
  37970. }
  37971. // result
  37972. VertexData.ComputeNormals(positions, indices, normals);
  37973. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37974. var vertexData = new VertexData();
  37975. vertexData.indices = indices;
  37976. vertexData.positions = positions;
  37977. vertexData.normals = normals;
  37978. vertexData.uvs = uvs;
  37979. return vertexData;
  37980. };
  37981. /**
  37982. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37983. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37984. * @param polygon a mesh built from polygonTriangulation.build()
  37985. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37986. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37987. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37988. * @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)
  37989. * @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)
  37990. * @returns the VertexData of the Polygon
  37991. */
  37992. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37993. var faceUV = fUV || new Array(3);
  37994. var faceColors = fColors;
  37995. var colors = [];
  37996. // default face colors and UV if undefined
  37997. for (var f = 0; f < 3; f++) {
  37998. if (faceUV[f] === undefined) {
  37999. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38000. }
  38001. if (faceColors && faceColors[f] === undefined) {
  38002. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38003. }
  38004. }
  38005. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38006. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38007. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38008. var indices = polygon.getIndices();
  38009. // set face colours and textures
  38010. var idx = 0;
  38011. var face = 0;
  38012. for (var index = 0; index < normals.length; index += 3) {
  38013. //Edge Face no. 1
  38014. if (Math.abs(normals[index + 1]) < 0.001) {
  38015. face = 1;
  38016. }
  38017. //Top Face no. 0
  38018. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38019. face = 0;
  38020. }
  38021. //Bottom Face no. 2
  38022. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38023. face = 2;
  38024. }
  38025. idx = index / 3;
  38026. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38027. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38028. if (faceColors) {
  38029. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38030. }
  38031. }
  38032. // sides
  38033. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38034. // Result
  38035. var vertexData = new VertexData();
  38036. vertexData.indices = indices;
  38037. vertexData.positions = positions;
  38038. vertexData.normals = normals;
  38039. vertexData.uvs = uvs;
  38040. if (faceColors) {
  38041. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38042. vertexData.colors = totalColors;
  38043. }
  38044. return vertexData;
  38045. };
  38046. /**
  38047. * Creates the VertexData of the IcoSphere
  38048. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38049. * * radius the radius of the IcoSphere, optional default 1
  38050. * * radiusX allows stretching in the x direction, optional, default radius
  38051. * * radiusY allows stretching in the y direction, optional, default radius
  38052. * * radiusZ allows stretching in the z direction, optional, default radius
  38053. * * flat when true creates a flat shaded mesh, optional, default true
  38054. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38055. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38056. * * 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)
  38057. * * 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)
  38058. * @returns the VertexData of the IcoSphere
  38059. */
  38060. VertexData.CreateIcoSphere = function (options) {
  38061. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38062. var radius = options.radius || 1;
  38063. var flat = (options.flat === undefined) ? true : options.flat;
  38064. var subdivisions = options.subdivisions || 4;
  38065. var radiusX = options.radiusX || radius;
  38066. var radiusY = options.radiusY || radius;
  38067. var radiusZ = options.radiusZ || radius;
  38068. var t = (1 + Math.sqrt(5)) / 2;
  38069. // 12 vertex x,y,z
  38070. var ico_vertices = [
  38071. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38072. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38073. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38074. ];
  38075. // index of 3 vertex makes a face of icopshere
  38076. var ico_indices = [
  38077. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38078. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38079. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38080. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38081. ];
  38082. // vertex for uv have aliased position, not for UV
  38083. var vertices_unalias_id = [
  38084. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38085. // vertex alias
  38086. 0,
  38087. 2,
  38088. 3,
  38089. 3,
  38090. 3,
  38091. 4,
  38092. 7,
  38093. 8,
  38094. 9,
  38095. 9,
  38096. 10,
  38097. 11 // 23: B + 12
  38098. ];
  38099. // uv as integer step (not pixels !)
  38100. var ico_vertexuv = [
  38101. 5, 1, 3, 1, 6, 4, 0, 0,
  38102. 5, 3, 4, 2, 2, 2, 4, 0,
  38103. 2, 0, 1, 1, 6, 0, 6, 2,
  38104. // vertex alias (for same vertex on different faces)
  38105. 0, 4,
  38106. 3, 3,
  38107. 4, 4,
  38108. 3, 1,
  38109. 4, 2,
  38110. 4, 4,
  38111. 0, 2,
  38112. 1, 1,
  38113. 2, 2,
  38114. 3, 3,
  38115. 1, 3,
  38116. 2, 4 // 23: B + 12
  38117. ];
  38118. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38119. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38120. // First island of uv mapping
  38121. // v = 4h 3+ 2
  38122. // v = 3h 9+ 4
  38123. // v = 2h 9+ 5 B
  38124. // v = 1h 9 1 0
  38125. // v = 0h 3 8 7 A
  38126. // u = 0 1 2 3 4 5 6 *a
  38127. // Second island of uv mapping
  38128. // v = 4h 0+ B+ 4+
  38129. // v = 3h A+ 2+
  38130. // v = 2h 7+ 6 3+
  38131. // v = 1h 8+ 3+
  38132. // v = 0h
  38133. // u = 0 1 2 3 4 5 6 *a
  38134. // Face layout on texture UV mapping
  38135. // ============
  38136. // \ 4 /\ 16 / ======
  38137. // \ / \ / /\ 11 /
  38138. // \/ 7 \/ / \ /
  38139. // ======= / 10 \/
  38140. // /\ 17 /\ =======
  38141. // / \ / \ \ 15 /\
  38142. // / 8 \/ 12 \ \ / \
  38143. // ============ \/ 6 \
  38144. // \ 18 /\ ============
  38145. // \ / \ \ 5 /\ 0 /
  38146. // \/ 13 \ \ / \ /
  38147. // ======= \/ 1 \/
  38148. // =============
  38149. // /\ 19 /\ 2 /\
  38150. // / \ / \ / \
  38151. // / 14 \/ 9 \/ 3 \
  38152. // ===================
  38153. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38154. var ustep = 138 / 1024;
  38155. var vstep = 239 / 1024;
  38156. var uoffset = 60 / 1024;
  38157. var voffset = 26 / 1024;
  38158. // Second island should have margin, not to touch the first island
  38159. // avoid any borderline artefact in pixel rounding
  38160. var island_u_offset = -40 / 1024;
  38161. var island_v_offset = +20 / 1024;
  38162. // face is either island 0 or 1 :
  38163. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38164. var island = [
  38165. 0, 0, 0, 0, 1,
  38166. 0, 0, 1, 1, 0,
  38167. 0, 0, 1, 1, 0,
  38168. 0, 1, 1, 1, 0 // 15 - 19
  38169. ];
  38170. var indices = new Array();
  38171. var positions = new Array();
  38172. var normals = new Array();
  38173. var uvs = new Array();
  38174. var current_indice = 0;
  38175. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38176. var face_vertex_pos = new Array(3);
  38177. var face_vertex_uv = new Array(3);
  38178. var v012;
  38179. for (v012 = 0; v012 < 3; v012++) {
  38180. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38181. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38182. }
  38183. // create all with normals
  38184. for (var face = 0; face < 20; face++) {
  38185. // 3 vertex per face
  38186. for (v012 = 0; v012 < 3; v012++) {
  38187. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38188. var v_id = ico_indices[3 * face + v012];
  38189. // vertex have 3D position (x,y,z)
  38190. 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]);
  38191. // Normalize to get normal, then scale to radius
  38192. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38193. // uv Coordinates from vertex ID
  38194. 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);
  38195. }
  38196. // Subdivide the face (interpolate pos, norm, uv)
  38197. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38198. // - norm is linear interpolation of vertex corner normal
  38199. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38200. // - uv is linear interpolation
  38201. //
  38202. // Topology is as below for sub-divide by 2
  38203. // vertex shown as v0,v1,v2
  38204. // interp index is i1 to progress in range [v0,v1[
  38205. // interp index is i2 to progress in range [v0,v2[
  38206. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38207. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38208. //
  38209. //
  38210. // i2 v2
  38211. // ^ ^
  38212. // / / \
  38213. // / / \
  38214. // / / \
  38215. // / / (0,1) \
  38216. // / #---------\
  38217. // / / \ (0,0)'/ \
  38218. // / / \ / \
  38219. // / / \ / \
  38220. // / / (0,0) \ / (1,0) \
  38221. // / #---------#---------\
  38222. // v0 v1
  38223. //
  38224. // --------------------> i1
  38225. //
  38226. // interp of (i1,i2):
  38227. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38228. // along i1 : lerp(x0,x1, i1/(S-i2))
  38229. //
  38230. // centroid of triangle is needed to get help normal computation
  38231. // (c1,c2) are used for centroid location
  38232. var interp_vertex = function (i1, i2, c1, c2) {
  38233. // vertex is interpolated from
  38234. // - face_vertex_pos[0..2]
  38235. // - face_vertex_uv[0..2]
  38236. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38237. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38238. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38239. pos_interp.normalize();
  38240. var vertex_normal;
  38241. if (flat) {
  38242. // in flat mode, recalculate normal as face centroid normal
  38243. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38244. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38245. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38246. }
  38247. else {
  38248. // in smooth mode, recalculate normal from each single vertex position
  38249. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38250. }
  38251. // Vertex normal need correction due to X,Y,Z radius scaling
  38252. vertex_normal.x /= radiusX;
  38253. vertex_normal.y /= radiusY;
  38254. vertex_normal.z /= radiusZ;
  38255. vertex_normal.normalize();
  38256. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38257. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38258. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38259. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38260. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38261. uvs.push(uv_interp.x, uv_interp.y);
  38262. // push each vertex has member of a face
  38263. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38264. indices.push(current_indice);
  38265. current_indice++;
  38266. };
  38267. for (var i2 = 0; i2 < subdivisions; i2++) {
  38268. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38269. // face : (i1,i2) for /\ :
  38270. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38271. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38272. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38273. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38274. if (i1 + i2 + 1 < subdivisions) {
  38275. // face : (i1,i2)' for \/ :
  38276. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38277. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38278. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38279. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38280. }
  38281. }
  38282. }
  38283. }
  38284. // Sides
  38285. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38286. // Result
  38287. var vertexData = new VertexData();
  38288. vertexData.indices = indices;
  38289. vertexData.positions = positions;
  38290. vertexData.normals = normals;
  38291. vertexData.uvs = uvs;
  38292. return vertexData;
  38293. };
  38294. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38295. /**
  38296. * Creates the VertexData for a Polyhedron
  38297. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38298. * * type provided types are:
  38299. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38300. * * 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)
  38301. * * size the size of the IcoSphere, optional default 1
  38302. * * sizeX allows stretching in the x direction, optional, default size
  38303. * * sizeY allows stretching in the y direction, optional, default size
  38304. * * sizeZ allows stretching in the z direction, optional, default size
  38305. * * 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
  38306. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38307. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38308. * * flat when true creates a flat shaded mesh, optional, default true
  38309. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38310. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38311. * * 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)
  38312. * * 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)
  38313. * @returns the VertexData of the Polyhedron
  38314. */
  38315. VertexData.CreatePolyhedron = function (options) {
  38316. // provided polyhedron types :
  38317. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38318. // 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)
  38319. var polyhedra = [];
  38320. 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]] };
  38321. 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]] };
  38322. polyhedra[2] = {
  38323. 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]],
  38324. 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]]
  38325. };
  38326. polyhedra[3] = {
  38327. 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]],
  38328. 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]]
  38329. };
  38330. polyhedra[4] = {
  38331. 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]],
  38332. 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]]
  38333. };
  38334. 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]] };
  38335. 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]] };
  38336. 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]] };
  38337. 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]] };
  38338. 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]] };
  38339. 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]] };
  38340. 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]] };
  38341. 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]] };
  38342. 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]] };
  38343. polyhedra[14] = {
  38344. 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]],
  38345. 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]]
  38346. };
  38347. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38348. var size = options.size;
  38349. var sizeX = options.sizeX || size || 1;
  38350. var sizeY = options.sizeY || size || 1;
  38351. var sizeZ = options.sizeZ || size || 1;
  38352. var data = options.custom || polyhedra[type];
  38353. var nbfaces = data.face.length;
  38354. var faceUV = options.faceUV || new Array(nbfaces);
  38355. var faceColors = options.faceColors;
  38356. var flat = (options.flat === undefined) ? true : options.flat;
  38357. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38358. var positions = new Array();
  38359. var indices = new Array();
  38360. var normals = new Array();
  38361. var uvs = new Array();
  38362. var colors = new Array();
  38363. var index = 0;
  38364. var faceIdx = 0; // face cursor in the array "indexes"
  38365. var indexes = new Array();
  38366. var i = 0;
  38367. var f = 0;
  38368. var u, v, ang, x, y, tmp;
  38369. // default face colors and UV if undefined
  38370. if (flat) {
  38371. for (f = 0; f < nbfaces; f++) {
  38372. if (faceColors && faceColors[f] === undefined) {
  38373. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38374. }
  38375. if (faceUV && faceUV[f] === undefined) {
  38376. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38377. }
  38378. }
  38379. }
  38380. if (!flat) {
  38381. for (i = 0; i < data.vertex.length; i++) {
  38382. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38383. uvs.push(0, 0);
  38384. }
  38385. for (f = 0; f < nbfaces; f++) {
  38386. for (i = 0; i < data.face[f].length - 2; i++) {
  38387. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38388. }
  38389. }
  38390. }
  38391. else {
  38392. for (f = 0; f < nbfaces; f++) {
  38393. var fl = data.face[f].length; // number of vertices of the current face
  38394. ang = 2 * Math.PI / fl;
  38395. x = 0.5 * Math.tan(ang / 2);
  38396. y = 0.5;
  38397. // positions, uvs, colors
  38398. for (i = 0; i < fl; i++) {
  38399. // positions
  38400. 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);
  38401. indexes.push(index);
  38402. index++;
  38403. // uvs
  38404. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38405. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38406. uvs.push(u, v);
  38407. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38408. y = x * Math.sin(ang) + y * Math.cos(ang);
  38409. x = tmp;
  38410. // colors
  38411. if (faceColors) {
  38412. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38413. }
  38414. }
  38415. // indices from indexes
  38416. for (i = 0; i < fl - 2; i++) {
  38417. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38418. }
  38419. faceIdx += fl;
  38420. }
  38421. }
  38422. VertexData.ComputeNormals(positions, indices, normals);
  38423. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38424. var vertexData = new VertexData();
  38425. vertexData.positions = positions;
  38426. vertexData.indices = indices;
  38427. vertexData.normals = normals;
  38428. vertexData.uvs = uvs;
  38429. if (faceColors && flat) {
  38430. vertexData.colors = colors;
  38431. }
  38432. return vertexData;
  38433. };
  38434. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38435. /**
  38436. * Creates the VertexData for a TorusKnot
  38437. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38438. * * radius the radius of the torus knot, optional, default 2
  38439. * * tube the thickness of the tube, optional, default 0.5
  38440. * * radialSegments the number of sides on each tube segments, optional, default 32
  38441. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38442. * * p the number of windings around the z axis, optional, default 2
  38443. * * q the number of windings around the x axis, optional, default 3
  38444. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38445. * * 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)
  38446. * * 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)
  38447. * @returns the VertexData of the Torus Knot
  38448. */
  38449. VertexData.CreateTorusKnot = function (options) {
  38450. var indices = new Array();
  38451. var positions = new Array();
  38452. var normals = new Array();
  38453. var uvs = new Array();
  38454. var radius = options.radius || 2;
  38455. var tube = options.tube || 0.5;
  38456. var radialSegments = options.radialSegments || 32;
  38457. var tubularSegments = options.tubularSegments || 32;
  38458. var p = options.p || 2;
  38459. var q = options.q || 3;
  38460. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38461. // Helper
  38462. var getPos = function (angle) {
  38463. var cu = Math.cos(angle);
  38464. var su = Math.sin(angle);
  38465. var quOverP = q / p * angle;
  38466. var cs = Math.cos(quOverP);
  38467. var tx = radius * (2 + cs) * 0.5 * cu;
  38468. var ty = radius * (2 + cs) * su * 0.5;
  38469. var tz = radius * Math.sin(quOverP) * 0.5;
  38470. return new BABYLON.Vector3(tx, ty, tz);
  38471. };
  38472. // Vertices
  38473. var i;
  38474. var j;
  38475. for (i = 0; i <= radialSegments; i++) {
  38476. var modI = i % radialSegments;
  38477. var u = modI / radialSegments * 2 * p * Math.PI;
  38478. var p1 = getPos(u);
  38479. var p2 = getPos(u + 0.01);
  38480. var tang = p2.subtract(p1);
  38481. var n = p2.add(p1);
  38482. var bitan = BABYLON.Vector3.Cross(tang, n);
  38483. n = BABYLON.Vector3.Cross(bitan, tang);
  38484. bitan.normalize();
  38485. n.normalize();
  38486. for (j = 0; j < tubularSegments; j++) {
  38487. var modJ = j % tubularSegments;
  38488. var v = modJ / tubularSegments * 2 * Math.PI;
  38489. var cx = -tube * Math.cos(v);
  38490. var cy = tube * Math.sin(v);
  38491. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38492. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38493. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38494. uvs.push(i / radialSegments);
  38495. uvs.push(j / tubularSegments);
  38496. }
  38497. }
  38498. for (i = 0; i < radialSegments; i++) {
  38499. for (j = 0; j < tubularSegments; j++) {
  38500. var jNext = (j + 1) % tubularSegments;
  38501. var a = i * tubularSegments + j;
  38502. var b = (i + 1) * tubularSegments + j;
  38503. var c = (i + 1) * tubularSegments + jNext;
  38504. var d = i * tubularSegments + jNext;
  38505. indices.push(d);
  38506. indices.push(b);
  38507. indices.push(a);
  38508. indices.push(d);
  38509. indices.push(c);
  38510. indices.push(b);
  38511. }
  38512. }
  38513. // Normals
  38514. VertexData.ComputeNormals(positions, indices, normals);
  38515. // Sides
  38516. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38517. // Result
  38518. var vertexData = new VertexData();
  38519. vertexData.indices = indices;
  38520. vertexData.positions = positions;
  38521. vertexData.normals = normals;
  38522. vertexData.uvs = uvs;
  38523. return vertexData;
  38524. };
  38525. // Tools
  38526. /**
  38527. * Compute normals for given positions and indices
  38528. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38529. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38530. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38531. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38532. * * facetNormals : optional array of facet normals (vector3)
  38533. * * facetPositions : optional array of facet positions (vector3)
  38534. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38535. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38536. * * bInfo : optional bounding info, required for facetPartitioning computation
  38537. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38538. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38539. * * useRightHandedSystem: optional boolean to for right handed system computation
  38540. * * depthSort : optional boolean to enable the facet depth sort computation
  38541. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38542. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38543. */
  38544. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38545. // temporary scalar variables
  38546. var index = 0; // facet index
  38547. var p1p2x = 0.0; // p1p2 vector x coordinate
  38548. var p1p2y = 0.0; // p1p2 vector y coordinate
  38549. var p1p2z = 0.0; // p1p2 vector z coordinate
  38550. var p3p2x = 0.0; // p3p2 vector x coordinate
  38551. var p3p2y = 0.0; // p3p2 vector y coordinate
  38552. var p3p2z = 0.0; // p3p2 vector z coordinate
  38553. var faceNormalx = 0.0; // facet normal x coordinate
  38554. var faceNormaly = 0.0; // facet normal y coordinate
  38555. var faceNormalz = 0.0; // facet normal z coordinate
  38556. var length = 0.0; // facet normal length before normalization
  38557. var v1x = 0; // vector1 x index in the positions array
  38558. var v1y = 0; // vector1 y index in the positions array
  38559. var v1z = 0; // vector1 z index in the positions array
  38560. var v2x = 0; // vector2 x index in the positions array
  38561. var v2y = 0; // vector2 y index in the positions array
  38562. var v2z = 0; // vector2 z index in the positions array
  38563. var v3x = 0; // vector3 x index in the positions array
  38564. var v3y = 0; // vector3 y index in the positions array
  38565. var v3z = 0; // vector3 z index in the positions array
  38566. var computeFacetNormals = false;
  38567. var computeFacetPositions = false;
  38568. var computeFacetPartitioning = false;
  38569. var computeDepthSort = false;
  38570. var faceNormalSign = 1;
  38571. var ratio = 0;
  38572. var distanceTo = null;
  38573. if (options) {
  38574. computeFacetNormals = (options.facetNormals) ? true : false;
  38575. computeFacetPositions = (options.facetPositions) ? true : false;
  38576. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38577. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38578. ratio = options.ratio || 0;
  38579. computeDepthSort = (options.depthSort) ? true : false;
  38580. distanceTo = (options.distanceTo);
  38581. if (computeDepthSort) {
  38582. if (distanceTo === undefined) {
  38583. distanceTo = BABYLON.Vector3.Zero();
  38584. }
  38585. var depthSortedFacets = options.depthSortedFacets;
  38586. }
  38587. }
  38588. // facetPartitioning reinit if needed
  38589. var xSubRatio = 0;
  38590. var ySubRatio = 0;
  38591. var zSubRatio = 0;
  38592. var subSq = 0;
  38593. if (computeFacetPartitioning && options && options.bbSize) {
  38594. var ox = 0; // X partitioning index for facet position
  38595. var oy = 0; // Y partinioning index for facet position
  38596. var oz = 0; // Z partinioning index for facet position
  38597. var b1x = 0; // X partitioning index for facet v1 vertex
  38598. var b1y = 0; // Y partitioning index for facet v1 vertex
  38599. var b1z = 0; // z partitioning index for facet v1 vertex
  38600. var b2x = 0; // X partitioning index for facet v2 vertex
  38601. var b2y = 0; // Y partitioning index for facet v2 vertex
  38602. var b2z = 0; // Z partitioning index for facet v2 vertex
  38603. var b3x = 0; // X partitioning index for facet v3 vertex
  38604. var b3y = 0; // Y partitioning index for facet v3 vertex
  38605. var b3z = 0; // Z partitioning index for facet v3 vertex
  38606. var block_idx_o = 0; // facet barycenter block index
  38607. var block_idx_v1 = 0; // v1 vertex block index
  38608. var block_idx_v2 = 0; // v2 vertex block index
  38609. var block_idx_v3 = 0; // v3 vertex block index
  38610. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38611. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38612. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38613. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38614. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38615. subSq = options.subDiv.max * options.subDiv.max;
  38616. options.facetPartitioning.length = 0;
  38617. }
  38618. // reset the normals
  38619. for (index = 0; index < positions.length; index++) {
  38620. normals[index] = 0.0;
  38621. }
  38622. // Loop : 1 indice triplet = 1 facet
  38623. var nbFaces = (indices.length / 3) | 0;
  38624. for (index = 0; index < nbFaces; index++) {
  38625. // get the indexes of the coordinates of each vertex of the facet
  38626. v1x = indices[index * 3] * 3;
  38627. v1y = v1x + 1;
  38628. v1z = v1x + 2;
  38629. v2x = indices[index * 3 + 1] * 3;
  38630. v2y = v2x + 1;
  38631. v2z = v2x + 2;
  38632. v3x = indices[index * 3 + 2] * 3;
  38633. v3y = v3x + 1;
  38634. v3z = v3x + 2;
  38635. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38636. p1p2y = positions[v1y] - positions[v2y];
  38637. p1p2z = positions[v1z] - positions[v2z];
  38638. p3p2x = positions[v3x] - positions[v2x];
  38639. p3p2y = positions[v3y] - positions[v2y];
  38640. p3p2z = positions[v3z] - positions[v2z];
  38641. // compute the face normal with the cross product
  38642. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38643. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38644. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38645. // normalize this normal and store it in the array facetData
  38646. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38647. length = (length === 0) ? 1.0 : length;
  38648. faceNormalx /= length;
  38649. faceNormaly /= length;
  38650. faceNormalz /= length;
  38651. if (computeFacetNormals && options) {
  38652. options.facetNormals[index].x = faceNormalx;
  38653. options.facetNormals[index].y = faceNormaly;
  38654. options.facetNormals[index].z = faceNormalz;
  38655. }
  38656. if (computeFacetPositions && options) {
  38657. // compute and the facet barycenter coordinates in the array facetPositions
  38658. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38659. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38660. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38661. }
  38662. if (computeFacetPartitioning && options) {
  38663. // store the facet indexes in arrays in the main facetPartitioning array :
  38664. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38665. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38666. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38667. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38668. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38669. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38670. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38671. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38672. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38673. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38674. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38675. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38676. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38677. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38678. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38679. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38680. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38681. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38682. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38683. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38684. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38685. // push each facet index in each block containing the vertex
  38686. options.facetPartitioning[block_idx_v1].push(index);
  38687. if (block_idx_v2 != block_idx_v1) {
  38688. options.facetPartitioning[block_idx_v2].push(index);
  38689. }
  38690. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38691. options.facetPartitioning[block_idx_v3].push(index);
  38692. }
  38693. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38694. options.facetPartitioning[block_idx_o].push(index);
  38695. }
  38696. }
  38697. if (computeDepthSort && options && options.facetPositions) {
  38698. var dsf = depthSortedFacets[index];
  38699. dsf.ind = index * 3;
  38700. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38701. }
  38702. // compute the normals anyway
  38703. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38704. normals[v1y] += faceNormaly;
  38705. normals[v1z] += faceNormalz;
  38706. normals[v2x] += faceNormalx;
  38707. normals[v2y] += faceNormaly;
  38708. normals[v2z] += faceNormalz;
  38709. normals[v3x] += faceNormalx;
  38710. normals[v3y] += faceNormaly;
  38711. normals[v3z] += faceNormalz;
  38712. }
  38713. // last normalization of each normal
  38714. for (index = 0; index < normals.length / 3; index++) {
  38715. faceNormalx = normals[index * 3];
  38716. faceNormaly = normals[index * 3 + 1];
  38717. faceNormalz = normals[index * 3 + 2];
  38718. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38719. length = (length === 0) ? 1.0 : length;
  38720. faceNormalx /= length;
  38721. faceNormaly /= length;
  38722. faceNormalz /= length;
  38723. normals[index * 3] = faceNormalx;
  38724. normals[index * 3 + 1] = faceNormaly;
  38725. normals[index * 3 + 2] = faceNormalz;
  38726. }
  38727. };
  38728. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38729. var li = indices.length;
  38730. var ln = normals.length;
  38731. var i;
  38732. var n;
  38733. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38734. switch (sideOrientation) {
  38735. case BABYLON.Mesh.FRONTSIDE:
  38736. // nothing changed
  38737. break;
  38738. case BABYLON.Mesh.BACKSIDE:
  38739. var tmp;
  38740. // indices
  38741. for (i = 0; i < li; i += 3) {
  38742. tmp = indices[i];
  38743. indices[i] = indices[i + 2];
  38744. indices[i + 2] = tmp;
  38745. }
  38746. // normals
  38747. for (n = 0; n < ln; n++) {
  38748. normals[n] = -normals[n];
  38749. }
  38750. break;
  38751. case BABYLON.Mesh.DOUBLESIDE:
  38752. // positions
  38753. var lp = positions.length;
  38754. var l = lp / 3;
  38755. for (var p = 0; p < lp; p++) {
  38756. positions[lp + p] = positions[p];
  38757. }
  38758. // indices
  38759. for (i = 0; i < li; i += 3) {
  38760. indices[i + li] = indices[i + 2] + l;
  38761. indices[i + 1 + li] = indices[i + 1] + l;
  38762. indices[i + 2 + li] = indices[i] + l;
  38763. }
  38764. // normals
  38765. for (n = 0; n < ln; n++) {
  38766. normals[ln + n] = -normals[n];
  38767. }
  38768. // uvs
  38769. var lu = uvs.length;
  38770. var u = 0;
  38771. for (u = 0; u < lu; u++) {
  38772. uvs[u + lu] = uvs[u];
  38773. }
  38774. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38775. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38776. u = 0;
  38777. for (i = 0; i < lu / 2; i++) {
  38778. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38779. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38780. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38781. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38782. u += 2;
  38783. }
  38784. break;
  38785. }
  38786. };
  38787. /**
  38788. * Applies VertexData created from the imported parameters to the geometry
  38789. * @param parsedVertexData the parsed data from an imported file
  38790. * @param geometry the geometry to apply the VertexData to
  38791. */
  38792. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38793. var vertexData = new VertexData();
  38794. // positions
  38795. var positions = parsedVertexData.positions;
  38796. if (positions) {
  38797. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38798. }
  38799. // normals
  38800. var normals = parsedVertexData.normals;
  38801. if (normals) {
  38802. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38803. }
  38804. // tangents
  38805. var tangents = parsedVertexData.tangents;
  38806. if (tangents) {
  38807. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38808. }
  38809. // uvs
  38810. var uvs = parsedVertexData.uvs;
  38811. if (uvs) {
  38812. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38813. }
  38814. // uv2s
  38815. var uv2s = parsedVertexData.uv2s;
  38816. if (uv2s) {
  38817. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38818. }
  38819. // uv3s
  38820. var uv3s = parsedVertexData.uv3s;
  38821. if (uv3s) {
  38822. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38823. }
  38824. // uv4s
  38825. var uv4s = parsedVertexData.uv4s;
  38826. if (uv4s) {
  38827. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38828. }
  38829. // uv5s
  38830. var uv5s = parsedVertexData.uv5s;
  38831. if (uv5s) {
  38832. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38833. }
  38834. // uv6s
  38835. var uv6s = parsedVertexData.uv6s;
  38836. if (uv6s) {
  38837. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38838. }
  38839. // colors
  38840. var colors = parsedVertexData.colors;
  38841. if (colors) {
  38842. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38843. }
  38844. // matricesIndices
  38845. var matricesIndices = parsedVertexData.matricesIndices;
  38846. if (matricesIndices) {
  38847. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38848. }
  38849. // matricesWeights
  38850. var matricesWeights = parsedVertexData.matricesWeights;
  38851. if (matricesWeights) {
  38852. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38853. }
  38854. // indices
  38855. var indices = parsedVertexData.indices;
  38856. if (indices) {
  38857. vertexData.indices = indices;
  38858. }
  38859. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38860. };
  38861. return VertexData;
  38862. }());
  38863. BABYLON.VertexData = VertexData;
  38864. })(BABYLON || (BABYLON = {}));
  38865. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38866. var BABYLON;
  38867. (function (BABYLON) {
  38868. /**
  38869. * Class used to store geometry data (vertex buffers + index buffer)
  38870. */
  38871. var Geometry = /** @class */ (function () {
  38872. /**
  38873. * Creates a new geometry
  38874. * @param id defines the unique ID
  38875. * @param scene defines the hosting scene
  38876. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38877. * @param updatable defines if geometry must be updatable (false by default)
  38878. * @param mesh defines the mesh that will be associated with the geometry
  38879. */
  38880. function Geometry(id, scene, vertexData, updatable, mesh) {
  38881. if (updatable === void 0) { updatable = false; }
  38882. if (mesh === void 0) { mesh = null; }
  38883. /**
  38884. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38885. */
  38886. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38887. this._totalVertices = 0;
  38888. this._isDisposed = false;
  38889. this._indexBufferIsUpdatable = false;
  38890. this.id = id;
  38891. this._engine = scene.getEngine();
  38892. this._meshes = [];
  38893. this._scene = scene;
  38894. //Init vertex buffer cache
  38895. this._vertexBuffers = {};
  38896. this._indices = [];
  38897. this._updatable = updatable;
  38898. // vertexData
  38899. if (vertexData) {
  38900. this.setAllVerticesData(vertexData, updatable);
  38901. }
  38902. else {
  38903. this._totalVertices = 0;
  38904. this._indices = [];
  38905. }
  38906. if (this._engine.getCaps().vertexArrayObject) {
  38907. this._vertexArrayObjects = {};
  38908. }
  38909. // applyToMesh
  38910. if (mesh) {
  38911. if (mesh.getClassName() === "LinesMesh") {
  38912. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38913. this._updateExtend();
  38914. }
  38915. this.applyToMesh(mesh);
  38916. mesh.computeWorldMatrix(true);
  38917. }
  38918. }
  38919. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38920. /**
  38921. * 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
  38922. */
  38923. get: function () {
  38924. return this._boundingBias;
  38925. },
  38926. /**
  38927. * 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
  38928. */
  38929. set: function (value) {
  38930. if (this._boundingBias && this._boundingBias.equals(value)) {
  38931. return;
  38932. }
  38933. this._boundingBias = value.clone();
  38934. this._updateBoundingInfo(true, null);
  38935. },
  38936. enumerable: true,
  38937. configurable: true
  38938. });
  38939. /**
  38940. * Static function used to attach a new empty geometry to a mesh
  38941. * @param mesh defines the mesh to attach the geometry to
  38942. * @returns the new {BABYLON.Geometry}
  38943. */
  38944. Geometry.CreateGeometryForMesh = function (mesh) {
  38945. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38946. geometry.applyToMesh(mesh);
  38947. return geometry;
  38948. };
  38949. Object.defineProperty(Geometry.prototype, "extend", {
  38950. /**
  38951. * Gets the current extend of the geometry
  38952. */
  38953. get: function () {
  38954. return this._extend;
  38955. },
  38956. enumerable: true,
  38957. configurable: true
  38958. });
  38959. /**
  38960. * Gets the hosting scene
  38961. * @returns the hosting {BABYLON.Scene}
  38962. */
  38963. Geometry.prototype.getScene = function () {
  38964. return this._scene;
  38965. };
  38966. /**
  38967. * Gets the hosting engine
  38968. * @returns the hosting {BABYLON.Engine}
  38969. */
  38970. Geometry.prototype.getEngine = function () {
  38971. return this._engine;
  38972. };
  38973. /**
  38974. * Defines if the geometry is ready to use
  38975. * @returns true if the geometry is ready to be used
  38976. */
  38977. Geometry.prototype.isReady = function () {
  38978. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38979. };
  38980. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38981. /**
  38982. * Gets a value indicating that the geometry should not be serialized
  38983. */
  38984. get: function () {
  38985. for (var index = 0; index < this._meshes.length; index++) {
  38986. if (!this._meshes[index].doNotSerialize) {
  38987. return false;
  38988. }
  38989. }
  38990. return true;
  38991. },
  38992. enumerable: true,
  38993. configurable: true
  38994. });
  38995. /** @hidden */
  38996. Geometry.prototype._rebuild = function () {
  38997. if (this._vertexArrayObjects) {
  38998. this._vertexArrayObjects = {};
  38999. }
  39000. // Index buffer
  39001. if (this._meshes.length !== 0 && this._indices) {
  39002. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39003. }
  39004. // Vertex buffers
  39005. for (var key in this._vertexBuffers) {
  39006. var vertexBuffer = this._vertexBuffers[key];
  39007. vertexBuffer._rebuild();
  39008. }
  39009. };
  39010. /**
  39011. * Affects all geometry data in one call
  39012. * @param vertexData defines the geometry data
  39013. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39014. */
  39015. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39016. vertexData.applyToGeometry(this, updatable);
  39017. this.notifyUpdate();
  39018. };
  39019. /**
  39020. * Set specific vertex data
  39021. * @param kind defines the data kind (Position, normal, etc...)
  39022. * @param data defines the vertex data to use
  39023. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39024. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39025. */
  39026. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39027. if (updatable === void 0) { updatable = false; }
  39028. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39029. this.setVerticesBuffer(buffer);
  39030. };
  39031. /**
  39032. * Removes a specific vertex data
  39033. * @param kind defines the data kind (Position, normal, etc...)
  39034. */
  39035. Geometry.prototype.removeVerticesData = function (kind) {
  39036. if (this._vertexBuffers[kind]) {
  39037. this._vertexBuffers[kind].dispose();
  39038. delete this._vertexBuffers[kind];
  39039. }
  39040. };
  39041. /**
  39042. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39043. * @param buffer defines the vertex buffer to use
  39044. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39045. */
  39046. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39047. if (totalVertices === void 0) { totalVertices = null; }
  39048. var kind = buffer.getKind();
  39049. if (this._vertexBuffers[kind]) {
  39050. this._vertexBuffers[kind].dispose();
  39051. }
  39052. this._vertexBuffers[kind] = buffer;
  39053. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39054. var data = buffer.getData();
  39055. if (totalVertices != null) {
  39056. this._totalVertices = totalVertices;
  39057. }
  39058. else {
  39059. if (data != null) {
  39060. this._totalVertices = data.length / (buffer.byteStride / 4);
  39061. }
  39062. }
  39063. this._updateExtend(data);
  39064. this._resetPointsArrayCache();
  39065. var meshes = this._meshes;
  39066. var numOfMeshes = meshes.length;
  39067. for (var index = 0; index < numOfMeshes; index++) {
  39068. var mesh = meshes[index];
  39069. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39070. mesh._createGlobalSubMesh(false);
  39071. mesh.computeWorldMatrix(true);
  39072. }
  39073. }
  39074. this.notifyUpdate(kind);
  39075. if (this._vertexArrayObjects) {
  39076. this._disposeVertexArrayObjects();
  39077. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39078. }
  39079. };
  39080. /**
  39081. * Update a specific vertex buffer
  39082. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39083. * It will do nothing if the buffer is not updatable
  39084. * @param kind defines the data kind (Position, normal, etc...)
  39085. * @param data defines the data to use
  39086. * @param offset defines the offset in the target buffer where to store the data
  39087. * @param useBytes set to true if the offset is in bytes
  39088. */
  39089. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39090. if (useBytes === void 0) { useBytes = false; }
  39091. var vertexBuffer = this.getVertexBuffer(kind);
  39092. if (!vertexBuffer) {
  39093. return;
  39094. }
  39095. vertexBuffer.updateDirectly(data, offset, useBytes);
  39096. this.notifyUpdate(kind);
  39097. };
  39098. /**
  39099. * Update a specific vertex buffer
  39100. * This function will create a new buffer if the current one is not updatable
  39101. * @param kind defines the data kind (Position, normal, etc...)
  39102. * @param data defines the data to use
  39103. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39104. */
  39105. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39106. if (updateExtends === void 0) { updateExtends = false; }
  39107. var vertexBuffer = this.getVertexBuffer(kind);
  39108. if (!vertexBuffer) {
  39109. return;
  39110. }
  39111. vertexBuffer.update(data);
  39112. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39113. this._updateBoundingInfo(updateExtends, data);
  39114. }
  39115. this.notifyUpdate(kind);
  39116. };
  39117. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39118. if (updateExtends) {
  39119. this._updateExtend(data);
  39120. }
  39121. var meshes = this._meshes;
  39122. var numOfMeshes = meshes.length;
  39123. this._resetPointsArrayCache();
  39124. for (var index = 0; index < numOfMeshes; index++) {
  39125. var mesh = meshes[index];
  39126. if (updateExtends) {
  39127. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39128. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39129. var subMesh = mesh.subMeshes[subIndex];
  39130. subMesh.refreshBoundingInfo();
  39131. }
  39132. }
  39133. }
  39134. };
  39135. /** @hidden */
  39136. Geometry.prototype._bind = function (effect, indexToBind) {
  39137. if (!effect) {
  39138. return;
  39139. }
  39140. if (indexToBind === undefined) {
  39141. indexToBind = this._indexBuffer;
  39142. }
  39143. var vbs = this.getVertexBuffers();
  39144. if (!vbs) {
  39145. return;
  39146. }
  39147. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39148. this._engine.bindBuffers(vbs, indexToBind, effect);
  39149. return;
  39150. }
  39151. // Using VAO
  39152. if (!this._vertexArrayObjects[effect.key]) {
  39153. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39154. }
  39155. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39156. };
  39157. /**
  39158. * Gets total number of vertices
  39159. * @returns the total number of vertices
  39160. */
  39161. Geometry.prototype.getTotalVertices = function () {
  39162. if (!this.isReady()) {
  39163. return 0;
  39164. }
  39165. return this._totalVertices;
  39166. };
  39167. /**
  39168. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39169. * @param kind defines the data kind (Position, normal, etc...)
  39170. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39171. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39172. * @returns a float array containing vertex data
  39173. */
  39174. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39175. var vertexBuffer = this.getVertexBuffer(kind);
  39176. if (!vertexBuffer) {
  39177. return null;
  39178. }
  39179. var data = vertexBuffer.getData();
  39180. if (!data) {
  39181. return null;
  39182. }
  39183. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39184. var count = this._totalVertices * vertexBuffer.getSize();
  39185. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39186. var copy_1 = new Array(count);
  39187. vertexBuffer.forEach(count, function (value, index) {
  39188. copy_1[index] = value;
  39189. });
  39190. return copy_1;
  39191. }
  39192. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39193. if (data instanceof Array) {
  39194. var offset = vertexBuffer.byteOffset / 4;
  39195. return BABYLON.Tools.Slice(data, offset, offset + count);
  39196. }
  39197. else if (data instanceof ArrayBuffer) {
  39198. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39199. }
  39200. else {
  39201. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39202. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39203. var result = new Float32Array(count);
  39204. var source = new Float32Array(data.buffer, offset, count);
  39205. result.set(source);
  39206. return result;
  39207. }
  39208. return new Float32Array(data.buffer, offset, count);
  39209. }
  39210. }
  39211. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39212. return BABYLON.Tools.Slice(data);
  39213. }
  39214. return data;
  39215. };
  39216. /**
  39217. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39218. * @param kind defines the data kind (Position, normal, etc...)
  39219. * @returns true if the vertex buffer with the specified kind is updatable
  39220. */
  39221. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39222. var vb = this._vertexBuffers[kind];
  39223. if (!vb) {
  39224. return false;
  39225. }
  39226. return vb.isUpdatable();
  39227. };
  39228. /**
  39229. * Gets a specific vertex buffer
  39230. * @param kind defines the data kind (Position, normal, etc...)
  39231. * @returns a {BABYLON.VertexBuffer}
  39232. */
  39233. Geometry.prototype.getVertexBuffer = function (kind) {
  39234. if (!this.isReady()) {
  39235. return null;
  39236. }
  39237. return this._vertexBuffers[kind];
  39238. };
  39239. /**
  39240. * Returns all vertex buffers
  39241. * @return an object holding all vertex buffers indexed by kind
  39242. */
  39243. Geometry.prototype.getVertexBuffers = function () {
  39244. if (!this.isReady()) {
  39245. return null;
  39246. }
  39247. return this._vertexBuffers;
  39248. };
  39249. /**
  39250. * Gets a boolean indicating if specific vertex buffer is present
  39251. * @param kind defines the data kind (Position, normal, etc...)
  39252. * @returns true if data is present
  39253. */
  39254. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39255. if (!this._vertexBuffers) {
  39256. if (this._delayInfo) {
  39257. return this._delayInfo.indexOf(kind) !== -1;
  39258. }
  39259. return false;
  39260. }
  39261. return this._vertexBuffers[kind] !== undefined;
  39262. };
  39263. /**
  39264. * Gets a list of all attached data kinds (Position, normal, etc...)
  39265. * @returns a list of string containing all kinds
  39266. */
  39267. Geometry.prototype.getVerticesDataKinds = function () {
  39268. var result = [];
  39269. var kind;
  39270. if (!this._vertexBuffers && this._delayInfo) {
  39271. for (kind in this._delayInfo) {
  39272. result.push(kind);
  39273. }
  39274. }
  39275. else {
  39276. for (kind in this._vertexBuffers) {
  39277. result.push(kind);
  39278. }
  39279. }
  39280. return result;
  39281. };
  39282. /**
  39283. * Update index buffer
  39284. * @param indices defines the indices to store in the index buffer
  39285. * @param offset defines the offset in the target buffer where to store the data
  39286. */
  39287. Geometry.prototype.updateIndices = function (indices, offset) {
  39288. if (!this._indexBuffer) {
  39289. return;
  39290. }
  39291. if (!this._indexBufferIsUpdatable) {
  39292. this.setIndices(indices, null, true);
  39293. }
  39294. else {
  39295. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39296. }
  39297. };
  39298. /**
  39299. * Creates a new index buffer
  39300. * @param indices defines the indices to store in the index buffer
  39301. * @param totalVertices defines the total number of vertices (could be null)
  39302. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39303. */
  39304. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39305. if (totalVertices === void 0) { totalVertices = null; }
  39306. if (updatable === void 0) { updatable = false; }
  39307. if (this._indexBuffer) {
  39308. this._engine._releaseBuffer(this._indexBuffer);
  39309. }
  39310. this._disposeVertexArrayObjects();
  39311. this._indices = indices;
  39312. this._indexBufferIsUpdatable = updatable;
  39313. if (this._meshes.length !== 0 && this._indices) {
  39314. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39315. }
  39316. if (totalVertices != undefined) { // including null and undefined
  39317. this._totalVertices = totalVertices;
  39318. }
  39319. var meshes = this._meshes;
  39320. var numOfMeshes = meshes.length;
  39321. for (var index = 0; index < numOfMeshes; index++) {
  39322. meshes[index]._createGlobalSubMesh(true);
  39323. }
  39324. this.notifyUpdate();
  39325. };
  39326. /**
  39327. * Return the total number of indices
  39328. * @returns the total number of indices
  39329. */
  39330. Geometry.prototype.getTotalIndices = function () {
  39331. if (!this.isReady()) {
  39332. return 0;
  39333. }
  39334. return this._indices.length;
  39335. };
  39336. /**
  39337. * Gets the index buffer array
  39338. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39339. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39340. * @returns the index buffer array
  39341. */
  39342. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39343. if (!this.isReady()) {
  39344. return null;
  39345. }
  39346. var orig = this._indices;
  39347. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39348. return orig;
  39349. }
  39350. else {
  39351. var len = orig.length;
  39352. var copy = [];
  39353. for (var i = 0; i < len; i++) {
  39354. copy.push(orig[i]);
  39355. }
  39356. return copy;
  39357. }
  39358. };
  39359. /**
  39360. * Gets the index buffer
  39361. * @return the index buffer
  39362. */
  39363. Geometry.prototype.getIndexBuffer = function () {
  39364. if (!this.isReady()) {
  39365. return null;
  39366. }
  39367. return this._indexBuffer;
  39368. };
  39369. /** @hidden */
  39370. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39371. if (effect === void 0) { effect = null; }
  39372. if (!effect || !this._vertexArrayObjects) {
  39373. return;
  39374. }
  39375. if (this._vertexArrayObjects[effect.key]) {
  39376. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39377. delete this._vertexArrayObjects[effect.key];
  39378. }
  39379. };
  39380. /**
  39381. * Release the associated resources for a specific mesh
  39382. * @param mesh defines the source mesh
  39383. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39384. */
  39385. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39386. var meshes = this._meshes;
  39387. var index = meshes.indexOf(mesh);
  39388. if (index === -1) {
  39389. return;
  39390. }
  39391. meshes.splice(index, 1);
  39392. mesh._geometry = null;
  39393. if (meshes.length === 0 && shouldDispose) {
  39394. this.dispose();
  39395. }
  39396. };
  39397. /**
  39398. * Apply current geometry to a given mesh
  39399. * @param mesh defines the mesh to apply geometry to
  39400. */
  39401. Geometry.prototype.applyToMesh = function (mesh) {
  39402. if (mesh._geometry === this) {
  39403. return;
  39404. }
  39405. var previousGeometry = mesh._geometry;
  39406. if (previousGeometry) {
  39407. previousGeometry.releaseForMesh(mesh);
  39408. }
  39409. var meshes = this._meshes;
  39410. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39411. mesh._geometry = this;
  39412. this._scene.pushGeometry(this);
  39413. meshes.push(mesh);
  39414. if (this.isReady()) {
  39415. this._applyToMesh(mesh);
  39416. }
  39417. else {
  39418. mesh._boundingInfo = this._boundingInfo;
  39419. }
  39420. };
  39421. Geometry.prototype._updateExtend = function (data) {
  39422. if (data === void 0) { data = null; }
  39423. if (!data) {
  39424. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39425. }
  39426. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39427. };
  39428. Geometry.prototype._applyToMesh = function (mesh) {
  39429. var numOfMeshes = this._meshes.length;
  39430. // vertexBuffers
  39431. for (var kind in this._vertexBuffers) {
  39432. if (numOfMeshes === 1) {
  39433. this._vertexBuffers[kind].create();
  39434. }
  39435. var buffer = this._vertexBuffers[kind].getBuffer();
  39436. if (buffer)
  39437. buffer.references = numOfMeshes;
  39438. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39439. if (!this._extend) {
  39440. this._updateExtend();
  39441. }
  39442. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39443. mesh._createGlobalSubMesh(false);
  39444. //bounding info was just created again, world matrix should be applied again.
  39445. mesh._updateBoundingInfo();
  39446. }
  39447. }
  39448. // indexBuffer
  39449. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39450. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39451. }
  39452. if (this._indexBuffer) {
  39453. this._indexBuffer.references = numOfMeshes;
  39454. }
  39455. };
  39456. Geometry.prototype.notifyUpdate = function (kind) {
  39457. if (this.onGeometryUpdated) {
  39458. this.onGeometryUpdated(this, kind);
  39459. }
  39460. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39461. var mesh = _a[_i];
  39462. mesh._markSubMeshesAsAttributesDirty();
  39463. }
  39464. };
  39465. /**
  39466. * Load the geometry if it was flagged as delay loaded
  39467. * @param scene defines the hosting scene
  39468. * @param onLoaded defines a callback called when the geometry is loaded
  39469. */
  39470. Geometry.prototype.load = function (scene, onLoaded) {
  39471. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39472. return;
  39473. }
  39474. if (this.isReady()) {
  39475. if (onLoaded) {
  39476. onLoaded();
  39477. }
  39478. return;
  39479. }
  39480. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39481. this._queueLoad(scene, onLoaded);
  39482. };
  39483. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39484. var _this = this;
  39485. if (!this.delayLoadingFile) {
  39486. return;
  39487. }
  39488. scene._addPendingData(this);
  39489. scene._loadFile(this.delayLoadingFile, function (data) {
  39490. if (!_this._delayLoadingFunction) {
  39491. return;
  39492. }
  39493. _this._delayLoadingFunction(JSON.parse(data), _this);
  39494. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39495. _this._delayInfo = [];
  39496. scene._removePendingData(_this);
  39497. var meshes = _this._meshes;
  39498. var numOfMeshes = meshes.length;
  39499. for (var index = 0; index < numOfMeshes; index++) {
  39500. _this._applyToMesh(meshes[index]);
  39501. }
  39502. if (onLoaded) {
  39503. onLoaded();
  39504. }
  39505. }, undefined, true);
  39506. };
  39507. /**
  39508. * Invert the geometry to move from a right handed system to a left handed one.
  39509. */
  39510. Geometry.prototype.toLeftHanded = function () {
  39511. // Flip faces
  39512. var tIndices = this.getIndices(false);
  39513. if (tIndices != null && tIndices.length > 0) {
  39514. for (var i = 0; i < tIndices.length; i += 3) {
  39515. var tTemp = tIndices[i + 0];
  39516. tIndices[i + 0] = tIndices[i + 2];
  39517. tIndices[i + 2] = tTemp;
  39518. }
  39519. this.setIndices(tIndices);
  39520. }
  39521. // Negate position.z
  39522. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39523. if (tPositions != null && tPositions.length > 0) {
  39524. for (var i = 0; i < tPositions.length; i += 3) {
  39525. tPositions[i + 2] = -tPositions[i + 2];
  39526. }
  39527. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39528. }
  39529. // Negate normal.z
  39530. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39531. if (tNormals != null && tNormals.length > 0) {
  39532. for (var i = 0; i < tNormals.length; i += 3) {
  39533. tNormals[i + 2] = -tNormals[i + 2];
  39534. }
  39535. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39536. }
  39537. };
  39538. // Cache
  39539. /** @hidden */
  39540. Geometry.prototype._resetPointsArrayCache = function () {
  39541. this._positions = null;
  39542. };
  39543. /** @hidden */
  39544. Geometry.prototype._generatePointsArray = function () {
  39545. if (this._positions)
  39546. return true;
  39547. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39548. if (!data || data.length === 0) {
  39549. return false;
  39550. }
  39551. this._positions = [];
  39552. for (var index = 0; index < data.length; index += 3) {
  39553. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39554. }
  39555. return true;
  39556. };
  39557. /**
  39558. * Gets a value indicating if the geometry is disposed
  39559. * @returns true if the geometry was disposed
  39560. */
  39561. Geometry.prototype.isDisposed = function () {
  39562. return this._isDisposed;
  39563. };
  39564. Geometry.prototype._disposeVertexArrayObjects = function () {
  39565. if (this._vertexArrayObjects) {
  39566. for (var kind in this._vertexArrayObjects) {
  39567. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39568. }
  39569. this._vertexArrayObjects = {};
  39570. }
  39571. };
  39572. /**
  39573. * Free all associated resources
  39574. */
  39575. Geometry.prototype.dispose = function () {
  39576. var meshes = this._meshes;
  39577. var numOfMeshes = meshes.length;
  39578. var index;
  39579. for (index = 0; index < numOfMeshes; index++) {
  39580. this.releaseForMesh(meshes[index]);
  39581. }
  39582. this._meshes = [];
  39583. this._disposeVertexArrayObjects();
  39584. for (var kind in this._vertexBuffers) {
  39585. this._vertexBuffers[kind].dispose();
  39586. }
  39587. this._vertexBuffers = {};
  39588. this._totalVertices = 0;
  39589. if (this._indexBuffer) {
  39590. this._engine._releaseBuffer(this._indexBuffer);
  39591. }
  39592. this._indexBuffer = null;
  39593. this._indices = [];
  39594. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39595. this.delayLoadingFile = null;
  39596. this._delayLoadingFunction = null;
  39597. this._delayInfo = [];
  39598. this._boundingInfo = null;
  39599. this._scene.removeGeometry(this);
  39600. this._isDisposed = true;
  39601. };
  39602. /**
  39603. * Clone the current geometry into a new geometry
  39604. * @param id defines the unique ID of the new geometry
  39605. * @returns a new geometry object
  39606. */
  39607. Geometry.prototype.copy = function (id) {
  39608. var vertexData = new BABYLON.VertexData();
  39609. vertexData.indices = [];
  39610. var indices = this.getIndices();
  39611. if (indices) {
  39612. for (var index = 0; index < indices.length; index++) {
  39613. vertexData.indices.push(indices[index]);
  39614. }
  39615. }
  39616. var updatable = false;
  39617. var stopChecking = false;
  39618. var kind;
  39619. for (kind in this._vertexBuffers) {
  39620. // using slice() to make a copy of the array and not just reference it
  39621. var data = this.getVerticesData(kind);
  39622. if (data instanceof Float32Array) {
  39623. vertexData.set(new Float32Array(data), kind);
  39624. }
  39625. else {
  39626. vertexData.set(data.slice(0), kind);
  39627. }
  39628. if (!stopChecking) {
  39629. var vb = this.getVertexBuffer(kind);
  39630. if (vb) {
  39631. updatable = vb.isUpdatable();
  39632. stopChecking = !updatable;
  39633. }
  39634. }
  39635. }
  39636. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39637. geometry.delayLoadState = this.delayLoadState;
  39638. geometry.delayLoadingFile = this.delayLoadingFile;
  39639. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39640. for (kind in this._delayInfo) {
  39641. geometry._delayInfo = geometry._delayInfo || [];
  39642. geometry._delayInfo.push(kind);
  39643. }
  39644. // Bounding info
  39645. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39646. return geometry;
  39647. };
  39648. /**
  39649. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39650. * @return a JSON representation of the current geometry data (without the vertices data)
  39651. */
  39652. Geometry.prototype.serialize = function () {
  39653. var serializationObject = {};
  39654. serializationObject.id = this.id;
  39655. serializationObject.updatable = this._updatable;
  39656. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39657. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39658. }
  39659. return serializationObject;
  39660. };
  39661. Geometry.prototype.toNumberArray = function (origin) {
  39662. if (Array.isArray(origin)) {
  39663. return origin;
  39664. }
  39665. else {
  39666. return Array.prototype.slice.call(origin);
  39667. }
  39668. };
  39669. /**
  39670. * Serialize all vertices data into a JSON oject
  39671. * @returns a JSON representation of the current geometry data
  39672. */
  39673. Geometry.prototype.serializeVerticeData = function () {
  39674. var serializationObject = this.serialize();
  39675. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39676. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39677. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39678. serializationObject.positions._updatable = true;
  39679. }
  39680. }
  39681. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39682. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39683. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39684. serializationObject.normals._updatable = true;
  39685. }
  39686. }
  39687. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39688. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39689. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39690. serializationObject.tangets._updatable = true;
  39691. }
  39692. }
  39693. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39694. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39695. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39696. serializationObject.uvs._updatable = true;
  39697. }
  39698. }
  39699. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39700. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39701. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39702. serializationObject.uv2s._updatable = true;
  39703. }
  39704. }
  39705. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39706. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39707. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39708. serializationObject.uv3s._updatable = true;
  39709. }
  39710. }
  39711. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39712. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39713. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39714. serializationObject.uv4s._updatable = true;
  39715. }
  39716. }
  39717. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39718. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39719. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39720. serializationObject.uv5s._updatable = true;
  39721. }
  39722. }
  39723. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39724. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39725. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39726. serializationObject.uv6s._updatable = true;
  39727. }
  39728. }
  39729. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39730. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39731. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39732. serializationObject.colors._updatable = true;
  39733. }
  39734. }
  39735. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39736. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39737. serializationObject.matricesIndices._isExpanded = true;
  39738. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39739. serializationObject.matricesIndices._updatable = true;
  39740. }
  39741. }
  39742. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39743. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39744. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39745. serializationObject.matricesWeights._updatable = true;
  39746. }
  39747. }
  39748. serializationObject.indices = this.toNumberArray(this.getIndices());
  39749. return serializationObject;
  39750. };
  39751. // Statics
  39752. /**
  39753. * Extracts a clone of a mesh geometry
  39754. * @param mesh defines the source mesh
  39755. * @param id defines the unique ID of the new geometry object
  39756. * @returns the new geometry object
  39757. */
  39758. Geometry.ExtractFromMesh = function (mesh, id) {
  39759. var geometry = mesh._geometry;
  39760. if (!geometry) {
  39761. return null;
  39762. }
  39763. return geometry.copy(id);
  39764. };
  39765. /**
  39766. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39767. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39768. * Be aware Math.random() could cause collisions, but:
  39769. * "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"
  39770. * @returns a string containing a new GUID
  39771. */
  39772. Geometry.RandomId = function () {
  39773. return BABYLON.Tools.RandomId();
  39774. };
  39775. /** @hidden */
  39776. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39777. var scene = mesh.getScene();
  39778. // Geometry
  39779. var geometryId = parsedGeometry.geometryId;
  39780. if (geometryId) {
  39781. var geometry = scene.getGeometryByID(geometryId);
  39782. if (geometry) {
  39783. geometry.applyToMesh(mesh);
  39784. }
  39785. }
  39786. else if (parsedGeometry instanceof ArrayBuffer) {
  39787. var binaryInfo = mesh._binaryInfo;
  39788. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39789. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39790. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39791. }
  39792. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39793. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39794. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39795. }
  39796. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39797. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39798. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39799. }
  39800. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39801. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39802. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39803. }
  39804. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39805. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39806. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39807. }
  39808. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39809. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39810. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39811. }
  39812. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39813. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39814. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39815. }
  39816. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39817. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39818. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39819. }
  39820. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39821. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39822. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39823. }
  39824. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39825. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39826. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39827. }
  39828. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39829. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39830. var floatIndices = [];
  39831. for (var i = 0; i < matricesIndicesData.length; i++) {
  39832. var index = matricesIndicesData[i];
  39833. floatIndices.push(index & 0x000000FF);
  39834. floatIndices.push((index & 0x0000FF00) >> 8);
  39835. floatIndices.push((index & 0x00FF0000) >> 16);
  39836. floatIndices.push(index >> 24);
  39837. }
  39838. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39839. }
  39840. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39841. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39842. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39843. }
  39844. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39845. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39846. mesh.setIndices(indicesData, null);
  39847. }
  39848. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39849. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39850. mesh.subMeshes = [];
  39851. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39852. var materialIndex = subMeshesData[(i * 5) + 0];
  39853. var verticesStart = subMeshesData[(i * 5) + 1];
  39854. var verticesCount = subMeshesData[(i * 5) + 2];
  39855. var indexStart = subMeshesData[(i * 5) + 3];
  39856. var indexCount = subMeshesData[(i * 5) + 4];
  39857. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39858. }
  39859. }
  39860. }
  39861. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39862. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39863. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39864. if (parsedGeometry.tangents) {
  39865. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39866. }
  39867. if (parsedGeometry.uvs) {
  39868. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39869. }
  39870. if (parsedGeometry.uvs2) {
  39871. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39872. }
  39873. if (parsedGeometry.uvs3) {
  39874. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39875. }
  39876. if (parsedGeometry.uvs4) {
  39877. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39878. }
  39879. if (parsedGeometry.uvs5) {
  39880. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39881. }
  39882. if (parsedGeometry.uvs6) {
  39883. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39884. }
  39885. if (parsedGeometry.colors) {
  39886. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39887. }
  39888. if (parsedGeometry.matricesIndices) {
  39889. if (!parsedGeometry.matricesIndices._isExpanded) {
  39890. var floatIndices = [];
  39891. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39892. var matricesIndex = parsedGeometry.matricesIndices[i];
  39893. floatIndices.push(matricesIndex & 0x000000FF);
  39894. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39895. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39896. floatIndices.push(matricesIndex >> 24);
  39897. }
  39898. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39899. }
  39900. else {
  39901. delete parsedGeometry.matricesIndices._isExpanded;
  39902. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39903. }
  39904. }
  39905. if (parsedGeometry.matricesIndicesExtra) {
  39906. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39907. var floatIndices = [];
  39908. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39909. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39910. floatIndices.push(matricesIndex & 0x000000FF);
  39911. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39912. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39913. floatIndices.push(matricesIndex >> 24);
  39914. }
  39915. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39916. }
  39917. else {
  39918. delete parsedGeometry.matricesIndices._isExpanded;
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39920. }
  39921. }
  39922. if (parsedGeometry.matricesWeights) {
  39923. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39924. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39925. }
  39926. if (parsedGeometry.matricesWeightsExtra) {
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39928. }
  39929. mesh.setIndices(parsedGeometry.indices, null);
  39930. }
  39931. // SubMeshes
  39932. if (parsedGeometry.subMeshes) {
  39933. mesh.subMeshes = [];
  39934. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39935. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39936. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39937. }
  39938. }
  39939. // Flat shading
  39940. if (mesh._shouldGenerateFlatShading) {
  39941. mesh.convertToFlatShadedMesh();
  39942. delete mesh._shouldGenerateFlatShading;
  39943. }
  39944. // Update
  39945. mesh.computeWorldMatrix(true);
  39946. // Octree
  39947. var sceneOctree = scene.selectionOctree;
  39948. if (sceneOctree !== undefined && sceneOctree !== null) {
  39949. sceneOctree.addMesh(mesh);
  39950. }
  39951. };
  39952. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39953. var epsilon = 1e-3;
  39954. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39955. return;
  39956. }
  39957. var noInfluenceBoneIndex = 0.0;
  39958. if (parsedGeometry.skeletonId > -1) {
  39959. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39960. if (!skeleton) {
  39961. return;
  39962. }
  39963. noInfluenceBoneIndex = skeleton.bones.length;
  39964. }
  39965. else {
  39966. return;
  39967. }
  39968. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39969. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39970. var matricesWeights = parsedGeometry.matricesWeights;
  39971. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39972. var influencers = parsedGeometry.numBoneInfluencer;
  39973. var size = matricesWeights.length;
  39974. for (var i = 0; i < size; i += 4) {
  39975. var weight = 0.0;
  39976. var firstZeroWeight = -1;
  39977. for (var j = 0; j < 4; j++) {
  39978. var w = matricesWeights[i + j];
  39979. weight += w;
  39980. if (w < epsilon && firstZeroWeight < 0) {
  39981. firstZeroWeight = j;
  39982. }
  39983. }
  39984. if (matricesWeightsExtra) {
  39985. for (var j = 0; j < 4; j++) {
  39986. var w = matricesWeightsExtra[i + j];
  39987. weight += w;
  39988. if (w < epsilon && firstZeroWeight < 0) {
  39989. firstZeroWeight = j + 4;
  39990. }
  39991. }
  39992. }
  39993. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39994. firstZeroWeight = influencers - 1;
  39995. }
  39996. if (weight > epsilon) {
  39997. var mweight = 1.0 / weight;
  39998. for (var j = 0; j < 4; j++) {
  39999. matricesWeights[i + j] *= mweight;
  40000. }
  40001. if (matricesWeightsExtra) {
  40002. for (var j = 0; j < 4; j++) {
  40003. matricesWeightsExtra[i + j] *= mweight;
  40004. }
  40005. }
  40006. }
  40007. else {
  40008. if (firstZeroWeight >= 4) {
  40009. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40010. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40011. }
  40012. else {
  40013. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40014. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40015. }
  40016. }
  40017. }
  40018. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40019. if (parsedGeometry.matricesWeightsExtra) {
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40021. }
  40022. };
  40023. /**
  40024. * Create a new geometry from persisted data (Using .babylon file format)
  40025. * @param parsedVertexData defines the persisted data
  40026. * @param scene defines the hosting scene
  40027. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40028. * @returns the new geometry object
  40029. */
  40030. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40031. if (scene.getGeometryByID(parsedVertexData.id)) {
  40032. return null; // null since geometry could be something else than a box...
  40033. }
  40034. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40035. if (BABYLON.Tags) {
  40036. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40037. }
  40038. if (parsedVertexData.delayLoadingFile) {
  40039. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40040. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40041. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40042. geometry._delayInfo = [];
  40043. if (parsedVertexData.hasUVs) {
  40044. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40045. }
  40046. if (parsedVertexData.hasUVs2) {
  40047. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40048. }
  40049. if (parsedVertexData.hasUVs3) {
  40050. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40051. }
  40052. if (parsedVertexData.hasUVs4) {
  40053. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40054. }
  40055. if (parsedVertexData.hasUVs5) {
  40056. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40057. }
  40058. if (parsedVertexData.hasUVs6) {
  40059. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40060. }
  40061. if (parsedVertexData.hasColors) {
  40062. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40063. }
  40064. if (parsedVertexData.hasMatricesIndices) {
  40065. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40066. }
  40067. if (parsedVertexData.hasMatricesWeights) {
  40068. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40069. }
  40070. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40071. }
  40072. else {
  40073. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40074. }
  40075. scene.pushGeometry(geometry, true);
  40076. return geometry;
  40077. };
  40078. return Geometry;
  40079. }());
  40080. BABYLON.Geometry = Geometry;
  40081. // Primitives
  40082. /// Abstract class
  40083. /**
  40084. * Abstract class used to provide common services for all typed geometries
  40085. * @hidden
  40086. */
  40087. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40088. __extends(_PrimitiveGeometry, _super);
  40089. /**
  40090. * Creates a new typed geometry
  40091. * @param id defines the unique ID of the geometry
  40092. * @param scene defines the hosting scene
  40093. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40094. * @param mesh defines the hosting mesh (can be null)
  40095. */
  40096. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40097. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40098. if (mesh === void 0) { mesh = null; }
  40099. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40100. _this._canBeRegenerated = _canBeRegenerated;
  40101. _this._beingRegenerated = true;
  40102. _this.regenerate();
  40103. _this._beingRegenerated = false;
  40104. return _this;
  40105. }
  40106. /**
  40107. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40108. * @returns true if the geometry can be regenerated
  40109. */
  40110. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40111. return this._canBeRegenerated;
  40112. };
  40113. /**
  40114. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40115. */
  40116. _PrimitiveGeometry.prototype.regenerate = function () {
  40117. if (!this._canBeRegenerated) {
  40118. return;
  40119. }
  40120. this._beingRegenerated = true;
  40121. this.setAllVerticesData(this._regenerateVertexData(), false);
  40122. this._beingRegenerated = false;
  40123. };
  40124. /**
  40125. * Clone the geometry
  40126. * @param id defines the unique ID of the new geometry
  40127. * @returns the new geometry
  40128. */
  40129. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40130. return _super.prototype.copy.call(this, id);
  40131. };
  40132. // overrides
  40133. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40134. if (!this._beingRegenerated) {
  40135. return;
  40136. }
  40137. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40138. };
  40139. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40140. if (!this._beingRegenerated) {
  40141. return;
  40142. }
  40143. _super.prototype.setVerticesData.call(this, kind, data, false);
  40144. };
  40145. // to override
  40146. /** @hidden */
  40147. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40148. throw new Error("Abstract method");
  40149. };
  40150. _PrimitiveGeometry.prototype.copy = function (id) {
  40151. throw new Error("Must be overriden in sub-classes.");
  40152. };
  40153. _PrimitiveGeometry.prototype.serialize = function () {
  40154. var serializationObject = _super.prototype.serialize.call(this);
  40155. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40156. return serializationObject;
  40157. };
  40158. return _PrimitiveGeometry;
  40159. }(Geometry));
  40160. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40161. /**
  40162. * Creates a ribbon geometry
  40163. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40164. */
  40165. var RibbonGeometry = /** @class */ (function (_super) {
  40166. __extends(RibbonGeometry, _super);
  40167. /**
  40168. * Creates a ribbon geometry
  40169. * @param id defines the unique ID of the geometry
  40170. * @param scene defines the hosting scene
  40171. * @param pathArray defines the array of paths to use
  40172. * @param closeArray defines if the last path and the first path must be joined
  40173. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40174. * @param offset defines the offset between points
  40175. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40176. * @param mesh defines the hosting mesh (can be null)
  40177. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40178. */
  40179. function RibbonGeometry(id, scene,
  40180. /**
  40181. * Defines the array of paths to use
  40182. */
  40183. pathArray,
  40184. /**
  40185. * Defines if the last and first points of each path in your pathArray must be joined
  40186. */
  40187. closeArray,
  40188. /**
  40189. * Defines if the last and first points of each path in your pathArray must be joined
  40190. */
  40191. closePath,
  40192. /**
  40193. * Defines the offset between points
  40194. */
  40195. offset, canBeRegenerated, mesh,
  40196. /**
  40197. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40198. */
  40199. side) {
  40200. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40201. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40202. _this.pathArray = pathArray;
  40203. _this.closeArray = closeArray;
  40204. _this.closePath = closePath;
  40205. _this.offset = offset;
  40206. _this.side = side;
  40207. return _this;
  40208. }
  40209. /** @hidden */
  40210. RibbonGeometry.prototype._regenerateVertexData = function () {
  40211. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40212. };
  40213. RibbonGeometry.prototype.copy = function (id) {
  40214. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40215. };
  40216. return RibbonGeometry;
  40217. }(_PrimitiveGeometry));
  40218. BABYLON.RibbonGeometry = RibbonGeometry;
  40219. /**
  40220. * Creates a box geometry
  40221. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40222. */
  40223. var BoxGeometry = /** @class */ (function (_super) {
  40224. __extends(BoxGeometry, _super);
  40225. /**
  40226. * Creates a box geometry
  40227. * @param id defines the unique ID of the geometry
  40228. * @param scene defines the hosting scene
  40229. * @param size defines the zise of the box (width, height and depth are the same)
  40230. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40231. * @param mesh defines the hosting mesh (can be null)
  40232. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40233. */
  40234. function BoxGeometry(id, scene,
  40235. /**
  40236. * Defines the zise of the box (width, height and depth are the same)
  40237. */
  40238. size, canBeRegenerated, mesh,
  40239. /**
  40240. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40241. */
  40242. side) {
  40243. if (mesh === void 0) { mesh = null; }
  40244. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40245. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40246. _this.size = size;
  40247. _this.side = side;
  40248. return _this;
  40249. }
  40250. /** @hidden */
  40251. BoxGeometry.prototype._regenerateVertexData = function () {
  40252. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40253. };
  40254. BoxGeometry.prototype.copy = function (id) {
  40255. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40256. };
  40257. BoxGeometry.prototype.serialize = function () {
  40258. var serializationObject = _super.prototype.serialize.call(this);
  40259. serializationObject.size = this.size;
  40260. return serializationObject;
  40261. };
  40262. BoxGeometry.Parse = function (parsedBox, scene) {
  40263. if (scene.getGeometryByID(parsedBox.id)) {
  40264. return null; // null since geometry could be something else than a box...
  40265. }
  40266. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40267. if (BABYLON.Tags) {
  40268. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40269. }
  40270. scene.pushGeometry(box, true);
  40271. return box;
  40272. };
  40273. return BoxGeometry;
  40274. }(_PrimitiveGeometry));
  40275. BABYLON.BoxGeometry = BoxGeometry;
  40276. /**
  40277. * Creates a sphere geometry
  40278. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40279. */
  40280. var SphereGeometry = /** @class */ (function (_super) {
  40281. __extends(SphereGeometry, _super);
  40282. /**
  40283. * Create a new sphere geometry
  40284. * @param id defines the unique ID of the geometry
  40285. * @param scene defines the hosting scene
  40286. * @param segments defines the number of segments to use to create the sphere
  40287. * @param diameter defines the diameter of the sphere
  40288. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40289. * @param mesh defines the hosting mesh (can be null)
  40290. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40291. */
  40292. function SphereGeometry(id, scene,
  40293. /**
  40294. * Defines the number of segments to use to create the sphere
  40295. */
  40296. segments,
  40297. /**
  40298. * Defines the diameter of the sphere
  40299. */
  40300. diameter, canBeRegenerated, mesh,
  40301. /**
  40302. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40303. */
  40304. side) {
  40305. if (mesh === void 0) { mesh = null; }
  40306. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40307. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40308. _this.segments = segments;
  40309. _this.diameter = diameter;
  40310. _this.side = side;
  40311. return _this;
  40312. }
  40313. /** @hidden */
  40314. SphereGeometry.prototype._regenerateVertexData = function () {
  40315. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40316. };
  40317. SphereGeometry.prototype.copy = function (id) {
  40318. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40319. };
  40320. SphereGeometry.prototype.serialize = function () {
  40321. var serializationObject = _super.prototype.serialize.call(this);
  40322. serializationObject.segments = this.segments;
  40323. serializationObject.diameter = this.diameter;
  40324. return serializationObject;
  40325. };
  40326. SphereGeometry.Parse = function (parsedSphere, scene) {
  40327. if (scene.getGeometryByID(parsedSphere.id)) {
  40328. return null; // null since geometry could be something else than a sphere...
  40329. }
  40330. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40331. if (BABYLON.Tags) {
  40332. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40333. }
  40334. scene.pushGeometry(sphere, true);
  40335. return sphere;
  40336. };
  40337. return SphereGeometry;
  40338. }(_PrimitiveGeometry));
  40339. BABYLON.SphereGeometry = SphereGeometry;
  40340. /**
  40341. * Creates a disc geometry
  40342. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40343. */
  40344. var DiscGeometry = /** @class */ (function (_super) {
  40345. __extends(DiscGeometry, _super);
  40346. /**
  40347. * Creates a new disc geometry
  40348. * @param id defines the unique ID of the geometry
  40349. * @param scene defines the hosting scene
  40350. * @param radius defines the radius of the disc
  40351. * @param tessellation defines the tesselation factor to apply to the disc
  40352. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40353. * @param mesh defines the hosting mesh (can be null)
  40354. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40355. */
  40356. function DiscGeometry(id, scene,
  40357. /**
  40358. * Defines the radius of the disc
  40359. */
  40360. radius,
  40361. /**
  40362. * Defines the tesselation factor to apply to the disc
  40363. */
  40364. tessellation, canBeRegenerated, mesh,
  40365. /**
  40366. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40367. */
  40368. side) {
  40369. if (mesh === void 0) { mesh = null; }
  40370. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40371. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40372. _this.radius = radius;
  40373. _this.tessellation = tessellation;
  40374. _this.side = side;
  40375. return _this;
  40376. }
  40377. /** @hidden */
  40378. DiscGeometry.prototype._regenerateVertexData = function () {
  40379. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40380. };
  40381. DiscGeometry.prototype.copy = function (id) {
  40382. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40383. };
  40384. return DiscGeometry;
  40385. }(_PrimitiveGeometry));
  40386. BABYLON.DiscGeometry = DiscGeometry;
  40387. /**
  40388. * Creates a new cylinder geometry
  40389. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40390. */
  40391. var CylinderGeometry = /** @class */ (function (_super) {
  40392. __extends(CylinderGeometry, _super);
  40393. /**
  40394. * Creates a new cylinder geometry
  40395. * @param id defines the unique ID of the geometry
  40396. * @param scene defines the hosting scene
  40397. * @param height defines the height of the cylinder
  40398. * @param diameterTop defines the diameter of the cylinder's top cap
  40399. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40400. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40401. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40402. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40403. * @param mesh defines the hosting mesh (can be null)
  40404. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40405. */
  40406. function CylinderGeometry(id, scene,
  40407. /**
  40408. * Defines the height of the cylinder
  40409. */
  40410. height,
  40411. /**
  40412. * Defines the diameter of the cylinder's top cap
  40413. */
  40414. diameterTop,
  40415. /**
  40416. * Defines the diameter of the cylinder's bottom cap
  40417. */
  40418. diameterBottom,
  40419. /**
  40420. * Defines the tessellation factor to apply to the cylinder
  40421. */
  40422. tessellation,
  40423. /**
  40424. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40425. */
  40426. subdivisions, canBeRegenerated, mesh,
  40427. /**
  40428. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40429. */
  40430. side) {
  40431. if (subdivisions === void 0) { subdivisions = 1; }
  40432. if (mesh === void 0) { mesh = null; }
  40433. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40434. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40435. _this.height = height;
  40436. _this.diameterTop = diameterTop;
  40437. _this.diameterBottom = diameterBottom;
  40438. _this.tessellation = tessellation;
  40439. _this.subdivisions = subdivisions;
  40440. _this.side = side;
  40441. return _this;
  40442. }
  40443. /** @hidden */
  40444. CylinderGeometry.prototype._regenerateVertexData = function () {
  40445. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40446. };
  40447. CylinderGeometry.prototype.copy = function (id) {
  40448. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40449. };
  40450. CylinderGeometry.prototype.serialize = function () {
  40451. var serializationObject = _super.prototype.serialize.call(this);
  40452. serializationObject.height = this.height;
  40453. serializationObject.diameterTop = this.diameterTop;
  40454. serializationObject.diameterBottom = this.diameterBottom;
  40455. serializationObject.tessellation = this.tessellation;
  40456. return serializationObject;
  40457. };
  40458. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40459. if (scene.getGeometryByID(parsedCylinder.id)) {
  40460. return null; // null since geometry could be something else than a cylinder...
  40461. }
  40462. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40463. if (BABYLON.Tags) {
  40464. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40465. }
  40466. scene.pushGeometry(cylinder, true);
  40467. return cylinder;
  40468. };
  40469. return CylinderGeometry;
  40470. }(_PrimitiveGeometry));
  40471. BABYLON.CylinderGeometry = CylinderGeometry;
  40472. /**
  40473. * Creates a new torus geometry
  40474. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40475. */
  40476. var TorusGeometry = /** @class */ (function (_super) {
  40477. __extends(TorusGeometry, _super);
  40478. /**
  40479. * Creates a new torus geometry
  40480. * @param id defines the unique ID of the geometry
  40481. * @param scene defines the hosting scene
  40482. * @param diameter defines the diameter of the torus
  40483. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40484. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40485. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40486. * @param mesh defines the hosting mesh (can be null)
  40487. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40488. */
  40489. function TorusGeometry(id, scene,
  40490. /**
  40491. * Defines the diameter of the torus
  40492. */
  40493. diameter,
  40494. /**
  40495. * Defines the thickness of the torus (ie. internal diameter)
  40496. */
  40497. thickness,
  40498. /**
  40499. * Defines the tesselation factor to apply to the torus
  40500. */
  40501. tessellation, canBeRegenerated, mesh,
  40502. /**
  40503. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40504. */
  40505. side) {
  40506. if (mesh === void 0) { mesh = null; }
  40507. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40508. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40509. _this.diameter = diameter;
  40510. _this.thickness = thickness;
  40511. _this.tessellation = tessellation;
  40512. _this.side = side;
  40513. return _this;
  40514. }
  40515. /** @hidden */
  40516. TorusGeometry.prototype._regenerateVertexData = function () {
  40517. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40518. };
  40519. TorusGeometry.prototype.copy = function (id) {
  40520. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40521. };
  40522. TorusGeometry.prototype.serialize = function () {
  40523. var serializationObject = _super.prototype.serialize.call(this);
  40524. serializationObject.diameter = this.diameter;
  40525. serializationObject.thickness = this.thickness;
  40526. serializationObject.tessellation = this.tessellation;
  40527. return serializationObject;
  40528. };
  40529. TorusGeometry.Parse = function (parsedTorus, scene) {
  40530. if (scene.getGeometryByID(parsedTorus.id)) {
  40531. return null; // null since geometry could be something else than a torus...
  40532. }
  40533. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40534. if (BABYLON.Tags) {
  40535. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40536. }
  40537. scene.pushGeometry(torus, true);
  40538. return torus;
  40539. };
  40540. return TorusGeometry;
  40541. }(_PrimitiveGeometry));
  40542. BABYLON.TorusGeometry = TorusGeometry;
  40543. /**
  40544. * Creates a new ground geometry
  40545. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40546. */
  40547. var GroundGeometry = /** @class */ (function (_super) {
  40548. __extends(GroundGeometry, _super);
  40549. /**
  40550. * Creates a new ground geometry
  40551. * @param id defines the unique ID of the geometry
  40552. * @param scene defines the hosting scene
  40553. * @param width defines the width of the ground
  40554. * @param height defines the height of the ground
  40555. * @param subdivisions defines the subdivisions to apply to the ground
  40556. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40557. * @param mesh defines the hosting mesh (can be null)
  40558. */
  40559. function GroundGeometry(id, scene,
  40560. /**
  40561. * Defines the width of the ground
  40562. */
  40563. width,
  40564. /**
  40565. * Defines the height of the ground
  40566. */
  40567. height,
  40568. /**
  40569. * Defines the subdivisions to apply to the ground
  40570. */
  40571. subdivisions, canBeRegenerated, mesh) {
  40572. if (mesh === void 0) { mesh = null; }
  40573. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40574. _this.width = width;
  40575. _this.height = height;
  40576. _this.subdivisions = subdivisions;
  40577. return _this;
  40578. }
  40579. /** @hidden */
  40580. GroundGeometry.prototype._regenerateVertexData = function () {
  40581. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40582. };
  40583. GroundGeometry.prototype.copy = function (id) {
  40584. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40585. };
  40586. GroundGeometry.prototype.serialize = function () {
  40587. var serializationObject = _super.prototype.serialize.call(this);
  40588. serializationObject.width = this.width;
  40589. serializationObject.height = this.height;
  40590. serializationObject.subdivisions = this.subdivisions;
  40591. return serializationObject;
  40592. };
  40593. GroundGeometry.Parse = function (parsedGround, scene) {
  40594. if (scene.getGeometryByID(parsedGround.id)) {
  40595. return null; // null since geometry could be something else than a ground...
  40596. }
  40597. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40598. if (BABYLON.Tags) {
  40599. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40600. }
  40601. scene.pushGeometry(ground, true);
  40602. return ground;
  40603. };
  40604. return GroundGeometry;
  40605. }(_PrimitiveGeometry));
  40606. BABYLON.GroundGeometry = GroundGeometry;
  40607. /**
  40608. * Creates a tiled ground geometry
  40609. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40610. */
  40611. var TiledGroundGeometry = /** @class */ (function (_super) {
  40612. __extends(TiledGroundGeometry, _super);
  40613. /**
  40614. * Creates a tiled ground geometry
  40615. * @param id defines the unique ID of the geometry
  40616. * @param scene defines the hosting scene
  40617. * @param xmin defines the minimum value on X axis
  40618. * @param zmin defines the minimum value on Z axis
  40619. * @param xmax defines the maximum value on X axis
  40620. * @param zmax defines the maximum value on Z axis
  40621. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40622. * @param precision defines the precision to use when computing the tiles
  40623. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40624. * @param mesh defines the hosting mesh (can be null)
  40625. */
  40626. function TiledGroundGeometry(id, scene,
  40627. /**
  40628. * Defines the minimum value on X axis
  40629. */
  40630. xmin,
  40631. /**
  40632. * Defines the minimum value on Z axis
  40633. */
  40634. zmin,
  40635. /**
  40636. * Defines the maximum value on X axis
  40637. */
  40638. xmax,
  40639. /**
  40640. * Defines the maximum value on Z axis
  40641. */
  40642. zmax,
  40643. /**
  40644. * Defines the subdivisions to apply to the ground
  40645. */
  40646. subdivisions,
  40647. /**
  40648. * Defines the precision to use when computing the tiles
  40649. */
  40650. precision, canBeRegenerated, mesh) {
  40651. if (mesh === void 0) { mesh = null; }
  40652. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40653. _this.xmin = xmin;
  40654. _this.zmin = zmin;
  40655. _this.xmax = xmax;
  40656. _this.zmax = zmax;
  40657. _this.subdivisions = subdivisions;
  40658. _this.precision = precision;
  40659. return _this;
  40660. }
  40661. /** @hidden */
  40662. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40663. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40664. };
  40665. TiledGroundGeometry.prototype.copy = function (id) {
  40666. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40667. };
  40668. return TiledGroundGeometry;
  40669. }(_PrimitiveGeometry));
  40670. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40671. /**
  40672. * Creates a plane geometry
  40673. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40674. */
  40675. var PlaneGeometry = /** @class */ (function (_super) {
  40676. __extends(PlaneGeometry, _super);
  40677. /**
  40678. * Creates a plane geometry
  40679. * @param id defines the unique ID of the geometry
  40680. * @param scene defines the hosting scene
  40681. * @param size defines the size of the plane (width === height)
  40682. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40683. * @param mesh defines the hosting mesh (can be null)
  40684. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40685. */
  40686. function PlaneGeometry(id, scene,
  40687. /**
  40688. * Defines the size of the plane (width === height)
  40689. */
  40690. size, canBeRegenerated, mesh,
  40691. /**
  40692. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40693. */
  40694. side) {
  40695. if (mesh === void 0) { mesh = null; }
  40696. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40697. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40698. _this.size = size;
  40699. _this.side = side;
  40700. return _this;
  40701. }
  40702. /** @hidden */
  40703. PlaneGeometry.prototype._regenerateVertexData = function () {
  40704. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40705. };
  40706. PlaneGeometry.prototype.copy = function (id) {
  40707. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40708. };
  40709. PlaneGeometry.prototype.serialize = function () {
  40710. var serializationObject = _super.prototype.serialize.call(this);
  40711. serializationObject.size = this.size;
  40712. return serializationObject;
  40713. };
  40714. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40715. if (scene.getGeometryByID(parsedPlane.id)) {
  40716. return null; // null since geometry could be something else than a ground...
  40717. }
  40718. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40719. if (BABYLON.Tags) {
  40720. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40721. }
  40722. scene.pushGeometry(plane, true);
  40723. return plane;
  40724. };
  40725. return PlaneGeometry;
  40726. }(_PrimitiveGeometry));
  40727. BABYLON.PlaneGeometry = PlaneGeometry;
  40728. /**
  40729. * Creates a torus knot geometry
  40730. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40731. */
  40732. var TorusKnotGeometry = /** @class */ (function (_super) {
  40733. __extends(TorusKnotGeometry, _super);
  40734. /**
  40735. * Creates a torus knot geometry
  40736. * @param id defines the unique ID of the geometry
  40737. * @param scene defines the hosting scene
  40738. * @param radius defines the radius of the torus knot
  40739. * @param tube defines the thickness of the torus knot tube
  40740. * @param radialSegments defines the number of radial segments
  40741. * @param tubularSegments defines the number of tubular segments
  40742. * @param p defines the first number of windings
  40743. * @param q defines the second number of windings
  40744. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40745. * @param mesh defines the hosting mesh (can be null)
  40746. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40747. */
  40748. function TorusKnotGeometry(id, scene,
  40749. /**
  40750. * Defines the radius of the torus knot
  40751. */
  40752. radius,
  40753. /**
  40754. * Defines the thickness of the torus knot tube
  40755. */
  40756. tube,
  40757. /**
  40758. * Defines the number of radial segments
  40759. */
  40760. radialSegments,
  40761. /**
  40762. * Defines the number of tubular segments
  40763. */
  40764. tubularSegments,
  40765. /**
  40766. * Defines the first number of windings
  40767. */
  40768. p,
  40769. /**
  40770. * Defines the second number of windings
  40771. */
  40772. q, canBeRegenerated, mesh,
  40773. /**
  40774. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40775. */
  40776. side) {
  40777. if (mesh === void 0) { mesh = null; }
  40778. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40779. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40780. _this.radius = radius;
  40781. _this.tube = tube;
  40782. _this.radialSegments = radialSegments;
  40783. _this.tubularSegments = tubularSegments;
  40784. _this.p = p;
  40785. _this.q = q;
  40786. _this.side = side;
  40787. return _this;
  40788. }
  40789. /** @hidden */
  40790. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40791. 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 });
  40792. };
  40793. TorusKnotGeometry.prototype.copy = function (id) {
  40794. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40795. };
  40796. TorusKnotGeometry.prototype.serialize = function () {
  40797. var serializationObject = _super.prototype.serialize.call(this);
  40798. serializationObject.radius = this.radius;
  40799. serializationObject.tube = this.tube;
  40800. serializationObject.radialSegments = this.radialSegments;
  40801. serializationObject.tubularSegments = this.tubularSegments;
  40802. serializationObject.p = this.p;
  40803. serializationObject.q = this.q;
  40804. return serializationObject;
  40805. };
  40806. ;
  40807. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40808. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40809. return null; // null since geometry could be something else than a ground...
  40810. }
  40811. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40812. if (BABYLON.Tags) {
  40813. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40814. }
  40815. scene.pushGeometry(torusKnot, true);
  40816. return torusKnot;
  40817. };
  40818. return TorusKnotGeometry;
  40819. }(_PrimitiveGeometry));
  40820. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40821. //}
  40822. })(BABYLON || (BABYLON = {}));
  40823. //# sourceMappingURL=babylon.geometry.js.map
  40824. var BABYLON;
  40825. (function (BABYLON) {
  40826. /**
  40827. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40828. */
  40829. var PerformanceMonitor = /** @class */ (function () {
  40830. /**
  40831. * constructor
  40832. * @param frameSampleSize The number of samples required to saturate the sliding window
  40833. */
  40834. function PerformanceMonitor(frameSampleSize) {
  40835. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40836. this._enabled = true;
  40837. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40838. }
  40839. /**
  40840. * Samples current frame
  40841. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40842. */
  40843. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40844. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40845. if (!this._enabled)
  40846. return;
  40847. if (this._lastFrameTimeMs != null) {
  40848. var dt = timeMs - this._lastFrameTimeMs;
  40849. this._rollingFrameTime.add(dt);
  40850. }
  40851. this._lastFrameTimeMs = timeMs;
  40852. };
  40853. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40854. /**
  40855. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40856. * @return Average frame time in milliseconds
  40857. */
  40858. get: function () {
  40859. return this._rollingFrameTime.average;
  40860. },
  40861. enumerable: true,
  40862. configurable: true
  40863. });
  40864. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40865. /**
  40866. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40867. * @return Frame time variance in milliseconds squared
  40868. */
  40869. get: function () {
  40870. return this._rollingFrameTime.variance;
  40871. },
  40872. enumerable: true,
  40873. configurable: true
  40874. });
  40875. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40876. /**
  40877. * Returns the frame time of the most recent frame
  40878. * @return Frame time in milliseconds
  40879. */
  40880. get: function () {
  40881. return this._rollingFrameTime.history(0);
  40882. },
  40883. enumerable: true,
  40884. configurable: true
  40885. });
  40886. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40887. /**
  40888. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40889. * @return Framerate in frames per second
  40890. */
  40891. get: function () {
  40892. return 1000.0 / this._rollingFrameTime.average;
  40893. },
  40894. enumerable: true,
  40895. configurable: true
  40896. });
  40897. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40898. /**
  40899. * Returns the average framerate in frames per second using the most recent frame time
  40900. * @return Framerate in frames per second
  40901. */
  40902. get: function () {
  40903. var history = this._rollingFrameTime.history(0);
  40904. if (history === 0) {
  40905. return 0;
  40906. }
  40907. return 1000.0 / history;
  40908. },
  40909. enumerable: true,
  40910. configurable: true
  40911. });
  40912. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40913. /**
  40914. * Returns true if enough samples have been taken to completely fill the sliding window
  40915. * @return true if saturated
  40916. */
  40917. get: function () {
  40918. return this._rollingFrameTime.isSaturated();
  40919. },
  40920. enumerable: true,
  40921. configurable: true
  40922. });
  40923. /**
  40924. * Enables contributions to the sliding window sample set
  40925. */
  40926. PerformanceMonitor.prototype.enable = function () {
  40927. this._enabled = true;
  40928. };
  40929. /**
  40930. * Disables contributions to the sliding window sample set
  40931. * Samples will not be interpolated over the disabled period
  40932. */
  40933. PerformanceMonitor.prototype.disable = function () {
  40934. this._enabled = false;
  40935. //clear last sample to avoid interpolating over the disabled period when next enabled
  40936. this._lastFrameTimeMs = null;
  40937. };
  40938. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40939. /**
  40940. * Returns true if sampling is enabled
  40941. * @return true if enabled
  40942. */
  40943. get: function () {
  40944. return this._enabled;
  40945. },
  40946. enumerable: true,
  40947. configurable: true
  40948. });
  40949. /**
  40950. * Resets performance monitor
  40951. */
  40952. PerformanceMonitor.prototype.reset = function () {
  40953. //clear last sample to avoid interpolating over the disabled period when next enabled
  40954. this._lastFrameTimeMs = null;
  40955. //wipe record
  40956. this._rollingFrameTime.reset();
  40957. };
  40958. return PerformanceMonitor;
  40959. }());
  40960. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40961. /**
  40962. * RollingAverage
  40963. *
  40964. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40965. */
  40966. var RollingAverage = /** @class */ (function () {
  40967. /**
  40968. * constructor
  40969. * @param length The number of samples required to saturate the sliding window
  40970. */
  40971. function RollingAverage(length) {
  40972. this._samples = new Array(length);
  40973. this.reset();
  40974. }
  40975. /**
  40976. * Adds a sample to the sample set
  40977. * @param v The sample value
  40978. */
  40979. RollingAverage.prototype.add = function (v) {
  40980. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40981. var delta;
  40982. //we need to check if we've already wrapped round
  40983. if (this.isSaturated()) {
  40984. //remove bottom of stack from mean
  40985. var bottomValue = this._samples[this._pos];
  40986. delta = bottomValue - this.average;
  40987. this.average -= delta / (this._sampleCount - 1);
  40988. this._m2 -= delta * (bottomValue - this.average);
  40989. }
  40990. else {
  40991. this._sampleCount++;
  40992. }
  40993. //add new value to mean
  40994. delta = v - this.average;
  40995. this.average += delta / (this._sampleCount);
  40996. this._m2 += delta * (v - this.average);
  40997. //set the new variance
  40998. this.variance = this._m2 / (this._sampleCount - 1);
  40999. this._samples[this._pos] = v;
  41000. this._pos++;
  41001. this._pos %= this._samples.length; //positive wrap around
  41002. };
  41003. /**
  41004. * Returns previously added values or null if outside of history or outside the sliding window domain
  41005. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41006. * @return Value previously recorded with add() or null if outside of range
  41007. */
  41008. RollingAverage.prototype.history = function (i) {
  41009. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41010. return 0;
  41011. }
  41012. var i0 = this._wrapPosition(this._pos - 1.0);
  41013. return this._samples[this._wrapPosition(i0 - i)];
  41014. };
  41015. /**
  41016. * Returns true if enough samples have been taken to completely fill the sliding window
  41017. * @return true if sample-set saturated
  41018. */
  41019. RollingAverage.prototype.isSaturated = function () {
  41020. return this._sampleCount >= this._samples.length;
  41021. };
  41022. /**
  41023. * Resets the rolling average (equivalent to 0 samples taken so far)
  41024. */
  41025. RollingAverage.prototype.reset = function () {
  41026. this.average = 0;
  41027. this.variance = 0;
  41028. this._sampleCount = 0;
  41029. this._pos = 0;
  41030. this._m2 = 0;
  41031. };
  41032. /**
  41033. * Wraps a value around the sample range boundaries
  41034. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41035. * @return Wrapped position in sample range
  41036. */
  41037. RollingAverage.prototype._wrapPosition = function (i) {
  41038. var max = this._samples.length;
  41039. return ((i % max) + max) % max;
  41040. };
  41041. return RollingAverage;
  41042. }());
  41043. BABYLON.RollingAverage = RollingAverage;
  41044. })(BABYLON || (BABYLON = {}));
  41045. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41046. var BABYLON;
  41047. (function (BABYLON) {
  41048. /**
  41049. * "Static Class" containing the most commonly used helper while dealing with material for
  41050. * rendering purpose.
  41051. *
  41052. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41053. *
  41054. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41055. */
  41056. var MaterialHelper = /** @class */ (function () {
  41057. function MaterialHelper() {
  41058. }
  41059. /**
  41060. * Bind the current view position to an effect.
  41061. * @param effect The effect to be bound
  41062. * @param scene The scene the eyes position is used from
  41063. */
  41064. MaterialHelper.BindEyePosition = function (effect, scene) {
  41065. if (scene._forcedViewPosition) {
  41066. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41067. return;
  41068. }
  41069. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41070. };
  41071. /**
  41072. * Helps preparing the defines values about the UVs in used in the effect.
  41073. * UVs are shared as much as we can accross chanels in the shaders.
  41074. * @param texture The texture we are preparing the UVs for
  41075. * @param defines The defines to update
  41076. * @param key The chanel key "diffuse", "specular"... used in the shader
  41077. */
  41078. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41079. defines._needUVs = true;
  41080. defines[key] = true;
  41081. if (texture.getTextureMatrix().isIdentity(true)) {
  41082. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41083. if (texture.coordinatesIndex === 0) {
  41084. defines["MAINUV1"] = true;
  41085. }
  41086. else {
  41087. defines["MAINUV2"] = true;
  41088. }
  41089. }
  41090. else {
  41091. defines[key + "DIRECTUV"] = 0;
  41092. }
  41093. };
  41094. /**
  41095. * Binds a texture matrix value to its corrsponding uniform
  41096. * @param texture The texture to bind the matrix for
  41097. * @param uniformBuffer The uniform buffer receivin the data
  41098. * @param key The chanel key "diffuse", "specular"... used in the shader
  41099. */
  41100. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41101. var matrix = texture.getTextureMatrix();
  41102. if (!matrix.isIdentity(true)) {
  41103. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41104. }
  41105. };
  41106. /**
  41107. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41108. * @param mesh defines the current mesh
  41109. * @param scene defines the current scene
  41110. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41111. * @param pointsCloud defines if point cloud rendering has to be turned on
  41112. * @param fogEnabled defines if fog has to be turned on
  41113. * @param alphaTest defines if alpha testing has to be turned on
  41114. * @param defines defines the current list of defines
  41115. */
  41116. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41117. if (defines._areMiscDirty) {
  41118. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41119. defines["POINTSIZE"] = pointsCloud;
  41120. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41121. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41122. defines["ALPHATEST"] = alphaTest;
  41123. }
  41124. };
  41125. /**
  41126. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41127. * @param scene defines the current scene
  41128. * @param engine defines the current engine
  41129. * @param defines specifies the list of active defines
  41130. * @param useInstances defines if instances have to be turned on
  41131. * @param useClipPlane defines if clip plane have to be turned on
  41132. */
  41133. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41134. if (useClipPlane === void 0) { useClipPlane = null; }
  41135. var changed = false;
  41136. var useClipPlane1 = false;
  41137. var useClipPlane2 = false;
  41138. var useClipPlane3 = false;
  41139. var useClipPlane4 = false;
  41140. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41141. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41142. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41143. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41144. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41145. defines["CLIPPLANE"] = useClipPlane1;
  41146. changed = true;
  41147. }
  41148. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41149. defines["CLIPPLANE2"] = useClipPlane2;
  41150. changed = true;
  41151. }
  41152. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41153. defines["CLIPPLANE3"] = useClipPlane3;
  41154. changed = true;
  41155. }
  41156. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41157. defines["CLIPPLANE4"] = useClipPlane4;
  41158. changed = true;
  41159. }
  41160. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41161. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41162. changed = true;
  41163. }
  41164. if (defines["INSTANCES"] !== useInstances) {
  41165. defines["INSTANCES"] = useInstances;
  41166. changed = true;
  41167. }
  41168. if (changed) {
  41169. defines.markAsUnprocessed();
  41170. }
  41171. };
  41172. /**
  41173. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41174. * @param mesh The mesh containing the geometry data we will draw
  41175. * @param defines The defines to update
  41176. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41177. * @param useBones Precise whether bones should be used or not (override mesh info)
  41178. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41179. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41180. * @returns false if defines are considered not dirty and have not been checked
  41181. */
  41182. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41183. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41184. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41185. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41186. return false;
  41187. }
  41188. defines._normals = defines._needNormals;
  41189. defines._uvs = defines._needUVs;
  41190. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41191. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41192. defines["TANGENT"] = true;
  41193. }
  41194. if (defines._needUVs) {
  41195. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41196. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41197. }
  41198. else {
  41199. defines["UV1"] = false;
  41200. defines["UV2"] = false;
  41201. }
  41202. if (useVertexColor) {
  41203. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41204. defines["VERTEXCOLOR"] = hasVertexColors;
  41205. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41206. }
  41207. if (useBones) {
  41208. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41209. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41210. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41211. }
  41212. else {
  41213. defines["NUM_BONE_INFLUENCERS"] = 0;
  41214. defines["BonesPerMesh"] = 0;
  41215. }
  41216. }
  41217. if (useMorphTargets) {
  41218. var manager = mesh.morphTargetManager;
  41219. if (manager) {
  41220. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41221. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41222. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41223. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41224. }
  41225. else {
  41226. defines["MORPHTARGETS_TANGENT"] = false;
  41227. defines["MORPHTARGETS_NORMAL"] = false;
  41228. defines["MORPHTARGETS"] = false;
  41229. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41230. }
  41231. }
  41232. return true;
  41233. };
  41234. /**
  41235. * Prepares the defines related to the light information passed in parameter
  41236. * @param scene The scene we are intending to draw
  41237. * @param mesh The mesh the effect is compiling for
  41238. * @param defines The defines to update
  41239. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41240. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41241. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41242. * @returns true if normals will be required for the rest of the effect
  41243. */
  41244. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41245. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41246. if (disableLighting === void 0) { disableLighting = false; }
  41247. if (!defines._areLightsDirty) {
  41248. return defines._needNormals;
  41249. }
  41250. var lightIndex = 0;
  41251. var needNormals = false;
  41252. var needRebuild = false;
  41253. var lightmapMode = false;
  41254. var shadowEnabled = false;
  41255. var specularEnabled = false;
  41256. if (scene.lightsEnabled && !disableLighting) {
  41257. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41258. var light = _a[_i];
  41259. needNormals = true;
  41260. if (defines["LIGHT" + lightIndex] === undefined) {
  41261. needRebuild = true;
  41262. }
  41263. defines["LIGHT" + lightIndex] = true;
  41264. defines["SPOTLIGHT" + lightIndex] = false;
  41265. defines["HEMILIGHT" + lightIndex] = false;
  41266. defines["POINTLIGHT" + lightIndex] = false;
  41267. defines["DIRLIGHT" + lightIndex] = false;
  41268. light.prepareLightSpecificDefines(defines, lightIndex);
  41269. // FallOff.
  41270. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41271. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41272. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41273. switch (light.falloffType) {
  41274. case BABYLON.Light.FALLOFF_GLTF:
  41275. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41276. break;
  41277. case BABYLON.Light.FALLOFF_PHYSICAL:
  41278. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41279. break;
  41280. case BABYLON.Light.FALLOFF_STANDARD:
  41281. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41282. break;
  41283. }
  41284. // Specular
  41285. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41286. specularEnabled = true;
  41287. }
  41288. // Shadows
  41289. defines["SHADOW" + lightIndex] = false;
  41290. defines["SHADOWPCF" + lightIndex] = false;
  41291. defines["SHADOWPCSS" + lightIndex] = false;
  41292. defines["SHADOWPOISSON" + lightIndex] = false;
  41293. defines["SHADOWESM" + lightIndex] = false;
  41294. defines["SHADOWCUBE" + lightIndex] = false;
  41295. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41296. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41297. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41298. var shadowGenerator = light.getShadowGenerator();
  41299. if (shadowGenerator) {
  41300. var shadowMap = shadowGenerator.getShadowMap();
  41301. if (shadowMap) {
  41302. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41303. shadowEnabled = true;
  41304. shadowGenerator.prepareDefines(defines, lightIndex);
  41305. }
  41306. }
  41307. }
  41308. }
  41309. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41310. lightmapMode = true;
  41311. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41312. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41313. }
  41314. else {
  41315. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41316. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41317. }
  41318. lightIndex++;
  41319. if (lightIndex === maxSimultaneousLights)
  41320. break;
  41321. }
  41322. }
  41323. defines["SPECULARTERM"] = specularEnabled;
  41324. defines["SHADOWS"] = shadowEnabled;
  41325. // Resetting all other lights if any
  41326. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41327. if (defines["LIGHT" + index] !== undefined) {
  41328. defines["LIGHT" + index] = false;
  41329. defines["HEMILIGHT" + lightIndex] = false;
  41330. defines["POINTLIGHT" + lightIndex] = false;
  41331. defines["DIRLIGHT" + lightIndex] = false;
  41332. defines["SPOTLIGHT" + lightIndex] = false;
  41333. defines["SHADOW" + lightIndex] = false;
  41334. }
  41335. }
  41336. var caps = scene.getEngine().getCaps();
  41337. if (defines["SHADOWFLOAT"] === undefined) {
  41338. needRebuild = true;
  41339. }
  41340. defines["SHADOWFLOAT"] = shadowEnabled &&
  41341. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41342. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41343. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41344. if (needRebuild) {
  41345. defines.rebuild();
  41346. }
  41347. return needNormals;
  41348. };
  41349. /**
  41350. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41351. * that won t be acctive due to defines being turned off.
  41352. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41353. * @param samplersList The samplers list
  41354. * @param defines The defines helping in the list generation
  41355. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41356. */
  41357. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41358. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41359. var uniformsList;
  41360. var uniformBuffersList = null;
  41361. if (uniformsListOrOptions.uniformsNames) {
  41362. var options = uniformsListOrOptions;
  41363. uniformsList = options.uniformsNames;
  41364. uniformBuffersList = options.uniformBuffersNames;
  41365. samplersList = options.samplers;
  41366. defines = options.defines;
  41367. maxSimultaneousLights = options.maxSimultaneousLights;
  41368. }
  41369. else {
  41370. uniformsList = uniformsListOrOptions;
  41371. if (!samplersList) {
  41372. samplersList = [];
  41373. }
  41374. }
  41375. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41376. if (!defines["LIGHT" + lightIndex]) {
  41377. break;
  41378. }
  41379. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41380. if (uniformBuffersList) {
  41381. uniformBuffersList.push("Light" + lightIndex);
  41382. }
  41383. samplersList.push("shadowSampler" + lightIndex);
  41384. samplersList.push("depthSampler" + lightIndex);
  41385. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41386. samplersList.push("projectionLightSampler" + lightIndex);
  41387. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41388. }
  41389. }
  41390. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41391. uniformsList.push("morphTargetInfluences");
  41392. }
  41393. };
  41394. /**
  41395. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41396. * @param defines The defines to update while falling back
  41397. * @param fallbacks The authorized effect fallbacks
  41398. * @param maxSimultaneousLights The maximum number of lights allowed
  41399. * @param rank the current rank of the Effect
  41400. * @returns The newly affected rank
  41401. */
  41402. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41403. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41404. if (rank === void 0) { rank = 0; }
  41405. var lightFallbackRank = 0;
  41406. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41407. if (!defines["LIGHT" + lightIndex]) {
  41408. break;
  41409. }
  41410. if (lightIndex > 0) {
  41411. lightFallbackRank = rank + lightIndex;
  41412. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41413. }
  41414. if (!defines["SHADOWS"]) {
  41415. if (defines["SHADOW" + lightIndex]) {
  41416. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41417. }
  41418. if (defines["SHADOWPCF" + lightIndex]) {
  41419. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41420. }
  41421. if (defines["SHADOWPCSS" + lightIndex]) {
  41422. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41423. }
  41424. if (defines["SHADOWPOISSON" + lightIndex]) {
  41425. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41426. }
  41427. if (defines["SHADOWESM" + lightIndex]) {
  41428. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41429. }
  41430. }
  41431. }
  41432. return lightFallbackRank++;
  41433. };
  41434. /**
  41435. * Prepares the list of attributes required for morph targets according to the effect defines.
  41436. * @param attribs The current list of supported attribs
  41437. * @param mesh The mesh to prepare the morph targets attributes for
  41438. * @param defines The current Defines of the effect
  41439. */
  41440. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41441. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41442. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41443. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41444. var manager = mesh.morphTargetManager;
  41445. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41446. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41447. for (var index = 0; index < influencers; index++) {
  41448. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41449. if (normal) {
  41450. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41451. }
  41452. if (tangent) {
  41453. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41454. }
  41455. if (attribs.length > maxAttributesCount) {
  41456. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41457. }
  41458. }
  41459. }
  41460. };
  41461. /**
  41462. * Prepares the list of attributes required for bones according to the effect defines.
  41463. * @param attribs The current list of supported attribs
  41464. * @param mesh The mesh to prepare the bones attributes for
  41465. * @param defines The current Defines of the effect
  41466. * @param fallbacks The current efffect fallback strategy
  41467. */
  41468. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41469. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41470. fallbacks.addCPUSkinningFallback(0, mesh);
  41471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41473. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41476. }
  41477. }
  41478. };
  41479. /**
  41480. * Prepares the list of attributes required for instances according to the effect defines.
  41481. * @param attribs The current list of supported attribs
  41482. * @param defines The current Defines of the effect
  41483. */
  41484. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41485. if (defines["INSTANCES"]) {
  41486. attribs.push("world0");
  41487. attribs.push("world1");
  41488. attribs.push("world2");
  41489. attribs.push("world3");
  41490. }
  41491. };
  41492. /**
  41493. * Binds the light shadow information to the effect for the given mesh.
  41494. * @param light The light containing the generator
  41495. * @param scene The scene the lights belongs to
  41496. * @param mesh The mesh we are binding the information to render
  41497. * @param lightIndex The light index in the effect used to render the mesh
  41498. * @param effect The effect we are binding the data to
  41499. */
  41500. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41501. if (light.shadowEnabled && mesh.receiveShadows) {
  41502. var shadowGenerator = light.getShadowGenerator();
  41503. if (shadowGenerator) {
  41504. shadowGenerator.bindShadowLight(lightIndex, effect);
  41505. }
  41506. }
  41507. };
  41508. /**
  41509. * Binds the light information to the effect.
  41510. * @param light The light containing the generator
  41511. * @param effect The effect we are binding the data to
  41512. * @param lightIndex The light index in the effect used to render
  41513. */
  41514. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41515. light.transferToEffect(effect, lightIndex + "");
  41516. };
  41517. /**
  41518. * Binds the lights information from the scene to the effect for the given mesh.
  41519. * @param scene The scene the lights belongs to
  41520. * @param mesh The mesh we are binding the information to render
  41521. * @param effect The effect we are binding the data to
  41522. * @param defines The generated defines for the effect
  41523. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41524. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41525. */
  41526. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41527. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41528. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41529. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41530. for (var i = 0; i < len; i++) {
  41531. var light = mesh._lightSources[i];
  41532. var iAsString = i.toString();
  41533. var scaledIntensity = light.getScaledIntensity();
  41534. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41535. MaterialHelper.BindLightProperties(light, effect, i);
  41536. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41537. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41538. if (defines["SPECULARTERM"]) {
  41539. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41540. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41541. }
  41542. // Shadows
  41543. if (scene.shadowsEnabled) {
  41544. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41545. }
  41546. light._uniformBuffer.update();
  41547. }
  41548. };
  41549. /**
  41550. * Binds the fog information from the scene to the effect for the given mesh.
  41551. * @param scene The scene the lights belongs to
  41552. * @param mesh The mesh we are binding the information to render
  41553. * @param effect The effect we are binding the data to
  41554. */
  41555. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41556. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41557. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41558. effect.setColor3("vFogColor", scene.fogColor);
  41559. }
  41560. };
  41561. /**
  41562. * Binds the bones information from the mesh to the effect.
  41563. * @param mesh The mesh we are binding the information to render
  41564. * @param effect The effect we are binding the data to
  41565. */
  41566. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41567. if (!effect || !mesh) {
  41568. return;
  41569. }
  41570. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41571. mesh.computeBonesUsingShaders = false;
  41572. }
  41573. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41574. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41575. if (matrices) {
  41576. effect.setMatrices("mBones", matrices);
  41577. }
  41578. }
  41579. };
  41580. /**
  41581. * Binds the morph targets information from the mesh to the effect.
  41582. * @param abstractMesh The mesh we are binding the information to render
  41583. * @param effect The effect we are binding the data to
  41584. */
  41585. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41586. var manager = abstractMesh.morphTargetManager;
  41587. if (!abstractMesh || !manager) {
  41588. return;
  41589. }
  41590. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41591. };
  41592. /**
  41593. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41594. * @param defines The generated defines used in the effect
  41595. * @param effect The effect we are binding the data to
  41596. * @param scene The scene we are willing to render with logarithmic scale for
  41597. */
  41598. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41599. if (defines["LOGARITHMICDEPTH"]) {
  41600. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41601. }
  41602. };
  41603. /**
  41604. * Binds the clip plane information from the scene to the effect.
  41605. * @param scene The scene the clip plane information are extracted from
  41606. * @param effect The effect we are binding the data to
  41607. */
  41608. MaterialHelper.BindClipPlane = function (effect, scene) {
  41609. if (scene.clipPlane) {
  41610. var clipPlane = scene.clipPlane;
  41611. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41612. }
  41613. if (scene.clipPlane2) {
  41614. var clipPlane = scene.clipPlane2;
  41615. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41616. }
  41617. if (scene.clipPlane3) {
  41618. var clipPlane = scene.clipPlane3;
  41619. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41620. }
  41621. if (scene.clipPlane4) {
  41622. var clipPlane = scene.clipPlane4;
  41623. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41624. }
  41625. };
  41626. return MaterialHelper;
  41627. }());
  41628. BABYLON.MaterialHelper = MaterialHelper;
  41629. })(BABYLON || (BABYLON = {}));
  41630. //# sourceMappingURL=babylon.materialHelper.js.map
  41631. var BABYLON;
  41632. (function (BABYLON) {
  41633. var PushMaterial = /** @class */ (function (_super) {
  41634. __extends(PushMaterial, _super);
  41635. function PushMaterial(name, scene) {
  41636. var _this = _super.call(this, name, scene) || this;
  41637. _this._normalMatrix = new BABYLON.Matrix();
  41638. _this.storeEffectOnSubMeshes = true;
  41639. return _this;
  41640. }
  41641. PushMaterial.prototype.getEffect = function () {
  41642. return this._activeEffect;
  41643. };
  41644. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41645. if (!mesh) {
  41646. return false;
  41647. }
  41648. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41649. return true;
  41650. }
  41651. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41652. };
  41653. /**
  41654. * Binds the given world matrix to the active effect
  41655. *
  41656. * @param world the matrix to bind
  41657. */
  41658. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41659. this._activeEffect.setMatrix("world", world);
  41660. };
  41661. /**
  41662. * Binds the given normal matrix to the active effect
  41663. *
  41664. * @param normalMatrix the matrix to bind
  41665. */
  41666. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41667. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41668. };
  41669. PushMaterial.prototype.bind = function (world, mesh) {
  41670. if (!mesh) {
  41671. return;
  41672. }
  41673. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41674. };
  41675. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41676. if (effect === void 0) { effect = null; }
  41677. _super.prototype._afterBind.call(this, mesh);
  41678. this.getScene()._cachedEffect = effect;
  41679. };
  41680. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41681. if (visibility === void 0) { visibility = 1; }
  41682. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41683. };
  41684. return PushMaterial;
  41685. }(BABYLON.Material));
  41686. BABYLON.PushMaterial = PushMaterial;
  41687. })(BABYLON || (BABYLON = {}));
  41688. //# sourceMappingURL=babylon.pushMaterial.js.map
  41689. var BABYLON;
  41690. (function (BABYLON) {
  41691. /** @hidden */
  41692. var StandardMaterialDefines = /** @class */ (function (_super) {
  41693. __extends(StandardMaterialDefines, _super);
  41694. function StandardMaterialDefines() {
  41695. var _this = _super.call(this) || this;
  41696. _this.MAINUV1 = false;
  41697. _this.MAINUV2 = false;
  41698. _this.DIFFUSE = false;
  41699. _this.DIFFUSEDIRECTUV = 0;
  41700. _this.AMBIENT = false;
  41701. _this.AMBIENTDIRECTUV = 0;
  41702. _this.OPACITY = false;
  41703. _this.OPACITYDIRECTUV = 0;
  41704. _this.OPACITYRGB = false;
  41705. _this.REFLECTION = false;
  41706. _this.EMISSIVE = false;
  41707. _this.EMISSIVEDIRECTUV = 0;
  41708. _this.SPECULAR = false;
  41709. _this.SPECULARDIRECTUV = 0;
  41710. _this.BUMP = false;
  41711. _this.BUMPDIRECTUV = 0;
  41712. _this.PARALLAX = false;
  41713. _this.PARALLAXOCCLUSION = false;
  41714. _this.SPECULAROVERALPHA = false;
  41715. _this.CLIPPLANE = false;
  41716. _this.CLIPPLANE2 = false;
  41717. _this.CLIPPLANE3 = false;
  41718. _this.CLIPPLANE4 = false;
  41719. _this.ALPHATEST = false;
  41720. _this.DEPTHPREPASS = false;
  41721. _this.ALPHAFROMDIFFUSE = false;
  41722. _this.POINTSIZE = false;
  41723. _this.FOG = false;
  41724. _this.SPECULARTERM = false;
  41725. _this.DIFFUSEFRESNEL = false;
  41726. _this.OPACITYFRESNEL = false;
  41727. _this.REFLECTIONFRESNEL = false;
  41728. _this.REFRACTIONFRESNEL = false;
  41729. _this.EMISSIVEFRESNEL = false;
  41730. _this.FRESNEL = false;
  41731. _this.NORMAL = false;
  41732. _this.UV1 = false;
  41733. _this.UV2 = false;
  41734. _this.VERTEXCOLOR = false;
  41735. _this.VERTEXALPHA = false;
  41736. _this.NUM_BONE_INFLUENCERS = 0;
  41737. _this.BonesPerMesh = 0;
  41738. _this.INSTANCES = false;
  41739. _this.GLOSSINESS = false;
  41740. _this.ROUGHNESS = false;
  41741. _this.EMISSIVEASILLUMINATION = false;
  41742. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41743. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41744. _this.LIGHTMAP = false;
  41745. _this.LIGHTMAPDIRECTUV = 0;
  41746. _this.OBJECTSPACE_NORMALMAP = false;
  41747. _this.USELIGHTMAPASSHADOWMAP = false;
  41748. _this.REFLECTIONMAP_3D = false;
  41749. _this.REFLECTIONMAP_SPHERICAL = false;
  41750. _this.REFLECTIONMAP_PLANAR = false;
  41751. _this.REFLECTIONMAP_CUBIC = false;
  41752. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41753. _this.REFLECTIONMAP_PROJECTION = false;
  41754. _this.REFLECTIONMAP_SKYBOX = false;
  41755. _this.REFLECTIONMAP_EXPLICIT = false;
  41756. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41757. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41758. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41759. _this.INVERTCUBICMAP = false;
  41760. _this.LOGARITHMICDEPTH = false;
  41761. _this.REFRACTION = false;
  41762. _this.REFRACTIONMAP_3D = false;
  41763. _this.REFLECTIONOVERALPHA = false;
  41764. _this.TWOSIDEDLIGHTING = false;
  41765. _this.SHADOWFLOAT = false;
  41766. _this.MORPHTARGETS = false;
  41767. _this.MORPHTARGETS_NORMAL = false;
  41768. _this.MORPHTARGETS_TANGENT = false;
  41769. _this.NUM_MORPH_INFLUENCERS = 0;
  41770. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41771. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41772. _this.IMAGEPROCESSING = false;
  41773. _this.VIGNETTE = false;
  41774. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41775. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41776. _this.TONEMAPPING = false;
  41777. _this.TONEMAPPING_ACES = false;
  41778. _this.CONTRAST = false;
  41779. _this.COLORCURVES = false;
  41780. _this.COLORGRADING = false;
  41781. _this.COLORGRADING3D = false;
  41782. _this.SAMPLER3DGREENDEPTH = false;
  41783. _this.SAMPLER3DBGRMAP = false;
  41784. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41785. /**
  41786. * If the reflection texture on this material is in linear color space
  41787. * @hidden
  41788. */
  41789. _this.IS_REFLECTION_LINEAR = false;
  41790. /**
  41791. * If the refraction texture on this material is in linear color space
  41792. * @hidden
  41793. */
  41794. _this.IS_REFRACTION_LINEAR = false;
  41795. _this.EXPOSURE = false;
  41796. _this.rebuild();
  41797. return _this;
  41798. }
  41799. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41800. var modes = [
  41801. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41802. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41803. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41804. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41805. ];
  41806. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41807. var mode = modes_1[_i];
  41808. this[mode] = (mode === modeToEnable);
  41809. }
  41810. };
  41811. return StandardMaterialDefines;
  41812. }(BABYLON.MaterialDefines));
  41813. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41814. var StandardMaterial = /** @class */ (function (_super) {
  41815. __extends(StandardMaterial, _super);
  41816. function StandardMaterial(name, scene) {
  41817. var _this = _super.call(this, name, scene) || this;
  41818. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41819. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41820. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41821. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41822. _this.specularPower = 64;
  41823. _this._useAlphaFromDiffuseTexture = false;
  41824. _this._useEmissiveAsIllumination = false;
  41825. _this._linkEmissiveWithDiffuse = false;
  41826. _this._useSpecularOverAlpha = false;
  41827. _this._useReflectionOverAlpha = false;
  41828. _this._disableLighting = false;
  41829. _this._useObjectSpaceNormalMap = false;
  41830. _this._useParallax = false;
  41831. _this._useParallaxOcclusion = false;
  41832. _this.parallaxScaleBias = 0.05;
  41833. _this._roughness = 0;
  41834. _this.indexOfRefraction = 0.98;
  41835. _this.invertRefractionY = true;
  41836. /**
  41837. * Defines the alpha limits in alpha test mode
  41838. */
  41839. _this.alphaCutOff = 0.4;
  41840. _this._useLightmapAsShadowmap = false;
  41841. _this._useReflectionFresnelFromSpecular = false;
  41842. _this._useGlossinessFromSpecularMapAlpha = false;
  41843. _this._maxSimultaneousLights = 4;
  41844. /**
  41845. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41846. */
  41847. _this._invertNormalMapX = false;
  41848. /**
  41849. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41850. */
  41851. _this._invertNormalMapY = false;
  41852. /**
  41853. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41854. */
  41855. _this._twoSidedLighting = false;
  41856. _this._renderTargets = new BABYLON.SmartArray(16);
  41857. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41858. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41859. // Setup the default processing configuration to the scene.
  41860. _this._attachImageProcessingConfiguration(null);
  41861. _this.getRenderTargetTextures = function () {
  41862. _this._renderTargets.reset();
  41863. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41864. _this._renderTargets.push(_this._reflectionTexture);
  41865. }
  41866. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41867. _this._renderTargets.push(_this._refractionTexture);
  41868. }
  41869. return _this._renderTargets;
  41870. };
  41871. return _this;
  41872. }
  41873. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41874. /**
  41875. * Gets the image processing configuration used either in this material.
  41876. */
  41877. get: function () {
  41878. return this._imageProcessingConfiguration;
  41879. },
  41880. /**
  41881. * Sets the Default image processing configuration used either in the this material.
  41882. *
  41883. * If sets to null, the scene one is in use.
  41884. */
  41885. set: function (value) {
  41886. this._attachImageProcessingConfiguration(value);
  41887. // Ensure the effect will be rebuilt.
  41888. this._markAllSubMeshesAsTexturesDirty();
  41889. },
  41890. enumerable: true,
  41891. configurable: true
  41892. });
  41893. /**
  41894. * Attaches a new image processing configuration to the Standard Material.
  41895. * @param configuration
  41896. */
  41897. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41898. var _this = this;
  41899. if (configuration === this._imageProcessingConfiguration) {
  41900. return;
  41901. }
  41902. // Detaches observer.
  41903. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41904. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41905. }
  41906. // Pick the scene configuration if needed.
  41907. if (!configuration) {
  41908. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41909. }
  41910. else {
  41911. this._imageProcessingConfiguration = configuration;
  41912. }
  41913. // Attaches observer.
  41914. if (this._imageProcessingConfiguration) {
  41915. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41916. _this._markAllSubMeshesAsImageProcessingDirty();
  41917. });
  41918. }
  41919. };
  41920. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41921. /**
  41922. * Gets wether the color curves effect is enabled.
  41923. */
  41924. get: function () {
  41925. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41926. },
  41927. /**
  41928. * Sets wether the color curves effect is enabled.
  41929. */
  41930. set: function (value) {
  41931. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41932. },
  41933. enumerable: true,
  41934. configurable: true
  41935. });
  41936. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41937. /**
  41938. * Gets wether the color grading effect is enabled.
  41939. */
  41940. get: function () {
  41941. return this.imageProcessingConfiguration.colorGradingEnabled;
  41942. },
  41943. /**
  41944. * Gets wether the color grading effect is enabled.
  41945. */
  41946. set: function (value) {
  41947. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41948. },
  41949. enumerable: true,
  41950. configurable: true
  41951. });
  41952. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41953. /**
  41954. * Gets wether tonemapping is enabled or not.
  41955. */
  41956. get: function () {
  41957. return this._imageProcessingConfiguration.toneMappingEnabled;
  41958. },
  41959. /**
  41960. * Sets wether tonemapping is enabled or not
  41961. */
  41962. set: function (value) {
  41963. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41964. },
  41965. enumerable: true,
  41966. configurable: true
  41967. });
  41968. ;
  41969. ;
  41970. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41971. /**
  41972. * The camera exposure used on this material.
  41973. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41974. * This corresponds to a photographic exposure.
  41975. */
  41976. get: function () {
  41977. return this._imageProcessingConfiguration.exposure;
  41978. },
  41979. /**
  41980. * The camera exposure used on this material.
  41981. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41982. * This corresponds to a photographic exposure.
  41983. */
  41984. set: function (value) {
  41985. this._imageProcessingConfiguration.exposure = value;
  41986. },
  41987. enumerable: true,
  41988. configurable: true
  41989. });
  41990. ;
  41991. ;
  41992. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41993. /**
  41994. * Gets The camera contrast used on this material.
  41995. */
  41996. get: function () {
  41997. return this._imageProcessingConfiguration.contrast;
  41998. },
  41999. /**
  42000. * Sets The camera contrast used on this material.
  42001. */
  42002. set: function (value) {
  42003. this._imageProcessingConfiguration.contrast = value;
  42004. },
  42005. enumerable: true,
  42006. configurable: true
  42007. });
  42008. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42009. /**
  42010. * Gets the Color Grading 2D Lookup Texture.
  42011. */
  42012. get: function () {
  42013. return this._imageProcessingConfiguration.colorGradingTexture;
  42014. },
  42015. /**
  42016. * Sets the Color Grading 2D Lookup Texture.
  42017. */
  42018. set: function (value) {
  42019. this._imageProcessingConfiguration.colorGradingTexture = value;
  42020. },
  42021. enumerable: true,
  42022. configurable: true
  42023. });
  42024. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42025. /**
  42026. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42027. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42028. * 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;
  42029. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42030. */
  42031. get: function () {
  42032. return this._imageProcessingConfiguration.colorCurves;
  42033. },
  42034. /**
  42035. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42036. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42037. * 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;
  42038. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42039. */
  42040. set: function (value) {
  42041. this._imageProcessingConfiguration.colorCurves = value;
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. StandardMaterial.prototype.getClassName = function () {
  42047. return "StandardMaterial";
  42048. };
  42049. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42050. get: function () {
  42051. return this._useLogarithmicDepth;
  42052. },
  42053. set: function (value) {
  42054. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42055. this._markAllSubMeshesAsMiscDirty();
  42056. },
  42057. enumerable: true,
  42058. configurable: true
  42059. });
  42060. StandardMaterial.prototype.needAlphaBlending = function () {
  42061. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42062. };
  42063. StandardMaterial.prototype.needAlphaTesting = function () {
  42064. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42065. };
  42066. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42067. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42068. };
  42069. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42070. return this._diffuseTexture;
  42071. };
  42072. /**
  42073. * Child classes can use it to update shaders
  42074. */
  42075. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42076. if (useInstances === void 0) { useInstances = false; }
  42077. if (subMesh.effect && this.isFrozen) {
  42078. if (this._wasPreviouslyReady) {
  42079. return true;
  42080. }
  42081. }
  42082. if (!subMesh._materialDefines) {
  42083. subMesh._materialDefines = new StandardMaterialDefines();
  42084. }
  42085. var scene = this.getScene();
  42086. var defines = subMesh._materialDefines;
  42087. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42088. if (defines._renderId === scene.getRenderId()) {
  42089. return true;
  42090. }
  42091. }
  42092. var engine = scene.getEngine();
  42093. // Lights
  42094. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42095. // Textures
  42096. if (defines._areTexturesDirty) {
  42097. defines._needUVs = false;
  42098. defines.MAINUV1 = false;
  42099. defines.MAINUV2 = false;
  42100. if (scene.texturesEnabled) {
  42101. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42102. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42103. return false;
  42104. }
  42105. else {
  42106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42107. }
  42108. }
  42109. else {
  42110. defines.DIFFUSE = false;
  42111. }
  42112. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42113. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42114. return false;
  42115. }
  42116. else {
  42117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42118. }
  42119. }
  42120. else {
  42121. defines.AMBIENT = false;
  42122. }
  42123. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42124. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42125. return false;
  42126. }
  42127. else {
  42128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42129. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42130. }
  42131. }
  42132. else {
  42133. defines.OPACITY = false;
  42134. }
  42135. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42136. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42137. return false;
  42138. }
  42139. else {
  42140. defines._needNormals = true;
  42141. defines.REFLECTION = true;
  42142. defines.ROUGHNESS = (this._roughness > 0);
  42143. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42144. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42145. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42146. switch (this._reflectionTexture.coordinatesMode) {
  42147. case BABYLON.Texture.EXPLICIT_MODE:
  42148. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42149. break;
  42150. case BABYLON.Texture.PLANAR_MODE:
  42151. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42152. break;
  42153. case BABYLON.Texture.PROJECTION_MODE:
  42154. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42155. break;
  42156. case BABYLON.Texture.SKYBOX_MODE:
  42157. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42158. break;
  42159. case BABYLON.Texture.SPHERICAL_MODE:
  42160. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42161. break;
  42162. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42163. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42164. break;
  42165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42166. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42167. break;
  42168. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42169. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42170. break;
  42171. case BABYLON.Texture.CUBIC_MODE:
  42172. case BABYLON.Texture.INVCUBIC_MODE:
  42173. default:
  42174. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42175. break;
  42176. }
  42177. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42178. }
  42179. }
  42180. else {
  42181. defines.REFLECTION = false;
  42182. }
  42183. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42184. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42185. return false;
  42186. }
  42187. else {
  42188. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42189. }
  42190. }
  42191. else {
  42192. defines.EMISSIVE = false;
  42193. }
  42194. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42195. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42196. return false;
  42197. }
  42198. else {
  42199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42200. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42201. }
  42202. }
  42203. else {
  42204. defines.LIGHTMAP = false;
  42205. }
  42206. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42207. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42208. return false;
  42209. }
  42210. else {
  42211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42212. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42213. }
  42214. }
  42215. else {
  42216. defines.SPECULAR = false;
  42217. }
  42218. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42219. // Bump texure can not be not blocking.
  42220. if (!this._bumpTexture.isReady()) {
  42221. return false;
  42222. }
  42223. else {
  42224. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42225. defines.PARALLAX = this._useParallax;
  42226. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42227. }
  42228. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42229. }
  42230. else {
  42231. defines.BUMP = false;
  42232. }
  42233. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42234. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42235. return false;
  42236. }
  42237. else {
  42238. defines._needUVs = true;
  42239. defines.REFRACTION = true;
  42240. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42241. }
  42242. }
  42243. else {
  42244. defines.REFRACTION = false;
  42245. }
  42246. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42247. }
  42248. else {
  42249. defines.DIFFUSE = false;
  42250. defines.AMBIENT = false;
  42251. defines.OPACITY = false;
  42252. defines.REFLECTION = false;
  42253. defines.EMISSIVE = false;
  42254. defines.LIGHTMAP = false;
  42255. defines.BUMP = false;
  42256. defines.REFRACTION = false;
  42257. }
  42258. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42259. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42260. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42261. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42262. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42263. }
  42264. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42265. if (!this._imageProcessingConfiguration.isReady()) {
  42266. return false;
  42267. }
  42268. this._imageProcessingConfiguration.prepareDefines(defines);
  42269. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42270. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42271. }
  42272. if (defines._areFresnelDirty) {
  42273. if (StandardMaterial.FresnelEnabled) {
  42274. // Fresnel
  42275. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42276. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42277. this._reflectionFresnelParameters) {
  42278. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42279. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42280. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42281. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42282. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42283. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42284. defines._needNormals = true;
  42285. defines.FRESNEL = true;
  42286. }
  42287. }
  42288. else {
  42289. defines.FRESNEL = false;
  42290. }
  42291. }
  42292. // Misc.
  42293. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42294. // Attribs
  42295. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42296. // Values that need to be evaluated on every frame
  42297. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42298. // Get correct effect
  42299. if (defines.isDirty) {
  42300. defines.markAsProcessed();
  42301. scene.resetCachedMaterial();
  42302. // Fallbacks
  42303. var fallbacks = new BABYLON.EffectFallbacks();
  42304. if (defines.REFLECTION) {
  42305. fallbacks.addFallback(0, "REFLECTION");
  42306. }
  42307. if (defines.SPECULAR) {
  42308. fallbacks.addFallback(0, "SPECULAR");
  42309. }
  42310. if (defines.BUMP) {
  42311. fallbacks.addFallback(0, "BUMP");
  42312. }
  42313. if (defines.PARALLAX) {
  42314. fallbacks.addFallback(1, "PARALLAX");
  42315. }
  42316. if (defines.PARALLAXOCCLUSION) {
  42317. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42318. }
  42319. if (defines.SPECULAROVERALPHA) {
  42320. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42321. }
  42322. if (defines.FOG) {
  42323. fallbacks.addFallback(1, "FOG");
  42324. }
  42325. if (defines.POINTSIZE) {
  42326. fallbacks.addFallback(0, "POINTSIZE");
  42327. }
  42328. if (defines.LOGARITHMICDEPTH) {
  42329. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42330. }
  42331. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42332. if (defines.SPECULARTERM) {
  42333. fallbacks.addFallback(0, "SPECULARTERM");
  42334. }
  42335. if (defines.DIFFUSEFRESNEL) {
  42336. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42337. }
  42338. if (defines.OPACITYFRESNEL) {
  42339. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42340. }
  42341. if (defines.REFLECTIONFRESNEL) {
  42342. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42343. }
  42344. if (defines.EMISSIVEFRESNEL) {
  42345. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42346. }
  42347. if (defines.FRESNEL) {
  42348. fallbacks.addFallback(4, "FRESNEL");
  42349. }
  42350. //Attributes
  42351. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42352. if (defines.NORMAL) {
  42353. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42354. }
  42355. if (defines.UV1) {
  42356. attribs.push(BABYLON.VertexBuffer.UVKind);
  42357. }
  42358. if (defines.UV2) {
  42359. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42360. }
  42361. if (defines.VERTEXCOLOR) {
  42362. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42363. }
  42364. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42365. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42366. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42367. var shaderName = "default";
  42368. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42369. "vFogInfos", "vFogColor", "pointSize",
  42370. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42371. "mBones",
  42372. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42373. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42374. "vReflectionPosition", "vReflectionSize",
  42375. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42376. ];
  42377. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42378. var uniformBuffers = ["Material", "Scene"];
  42379. if (BABYLON.ImageProcessingConfiguration) {
  42380. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42381. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42382. }
  42383. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42384. uniformsNames: uniforms,
  42385. uniformBuffersNames: uniformBuffers,
  42386. samplers: samplers,
  42387. defines: defines,
  42388. maxSimultaneousLights: this._maxSimultaneousLights
  42389. });
  42390. if (this.customShaderNameResolve) {
  42391. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42392. }
  42393. var join = defines.toString();
  42394. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42395. attributes: attribs,
  42396. uniformsNames: uniforms,
  42397. uniformBuffersNames: uniformBuffers,
  42398. samplers: samplers,
  42399. defines: join,
  42400. fallbacks: fallbacks,
  42401. onCompiled: this.onCompiled,
  42402. onError: this.onError,
  42403. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42404. }, engine), defines);
  42405. this.buildUniformLayout();
  42406. }
  42407. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42408. return false;
  42409. }
  42410. defines._renderId = scene.getRenderId();
  42411. this._wasPreviouslyReady = true;
  42412. return true;
  42413. };
  42414. StandardMaterial.prototype.buildUniformLayout = function () {
  42415. // Order is important !
  42416. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42417. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42418. this._uniformBuffer.addUniform("opacityParts", 4);
  42419. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42420. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42421. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42422. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42423. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42424. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42425. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42426. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42427. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42428. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42429. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42430. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42431. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42432. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42433. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42434. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42435. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42436. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42437. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42438. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42439. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42440. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42441. this._uniformBuffer.addUniform("specularMatrix", 16);
  42442. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42443. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42444. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42445. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42446. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42447. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42448. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42449. this._uniformBuffer.addUniform("pointSize", 1);
  42450. this._uniformBuffer.create();
  42451. };
  42452. StandardMaterial.prototype.unbind = function () {
  42453. if (this._activeEffect) {
  42454. var needFlag = false;
  42455. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42456. this._activeEffect.setTexture("reflection2DSampler", null);
  42457. needFlag = true;
  42458. }
  42459. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42460. this._activeEffect.setTexture("refraction2DSampler", null);
  42461. needFlag = true;
  42462. }
  42463. if (needFlag) {
  42464. this._markAllSubMeshesAsTexturesDirty();
  42465. }
  42466. }
  42467. _super.prototype.unbind.call(this);
  42468. };
  42469. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42470. var scene = this.getScene();
  42471. var defines = subMesh._materialDefines;
  42472. if (!defines) {
  42473. return;
  42474. }
  42475. var effect = subMesh.effect;
  42476. if (!effect) {
  42477. return;
  42478. }
  42479. this._activeEffect = effect;
  42480. // Matrices
  42481. this.bindOnlyWorldMatrix(world);
  42482. // Normal Matrix
  42483. if (defines.OBJECTSPACE_NORMALMAP) {
  42484. world.toNormalMatrix(this._normalMatrix);
  42485. this.bindOnlyNormalMatrix(this._normalMatrix);
  42486. }
  42487. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42488. // Bones
  42489. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42490. if (mustRebind) {
  42491. this._uniformBuffer.bindToEffect(effect, "Material");
  42492. this.bindViewProjection(effect);
  42493. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42494. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42495. // Fresnel
  42496. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42497. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42498. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42499. }
  42500. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42501. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42502. }
  42503. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42504. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42505. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42506. }
  42507. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42508. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42509. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42510. }
  42511. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42512. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42513. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42514. }
  42515. }
  42516. // Textures
  42517. if (scene.texturesEnabled) {
  42518. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42519. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42520. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42521. if (this._diffuseTexture.hasAlpha) {
  42522. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42523. }
  42524. }
  42525. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42526. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42527. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42528. }
  42529. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42530. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42531. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42532. }
  42533. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42534. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42535. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42536. if (this._reflectionTexture.boundingBoxSize) {
  42537. var cubeTexture = this._reflectionTexture;
  42538. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42539. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42540. }
  42541. }
  42542. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42543. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42544. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42545. }
  42546. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42547. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42548. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42549. }
  42550. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42551. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42552. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42553. }
  42554. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42555. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42556. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42557. if (scene._mirroredCameraPosition) {
  42558. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42559. }
  42560. else {
  42561. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42562. }
  42563. }
  42564. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42565. var depth = 1.0;
  42566. if (!this._refractionTexture.isCube) {
  42567. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42568. if (this._refractionTexture.depth) {
  42569. depth = this._refractionTexture.depth;
  42570. }
  42571. }
  42572. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42573. }
  42574. }
  42575. // Point size
  42576. if (this.pointsCloud) {
  42577. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42578. }
  42579. if (defines.SPECULARTERM) {
  42580. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42581. }
  42582. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42583. // Diffuse
  42584. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42585. }
  42586. // Textures
  42587. if (scene.texturesEnabled) {
  42588. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42589. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42590. }
  42591. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42592. effect.setTexture("ambientSampler", this._ambientTexture);
  42593. }
  42594. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42595. effect.setTexture("opacitySampler", this._opacityTexture);
  42596. }
  42597. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42598. if (this._reflectionTexture.isCube) {
  42599. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42600. }
  42601. else {
  42602. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42603. }
  42604. }
  42605. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42606. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42607. }
  42608. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42609. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42610. }
  42611. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42612. effect.setTexture("specularSampler", this._specularTexture);
  42613. }
  42614. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42615. effect.setTexture("bumpSampler", this._bumpTexture);
  42616. }
  42617. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42618. var depth = 1.0;
  42619. if (this._refractionTexture.isCube) {
  42620. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42621. }
  42622. else {
  42623. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42624. }
  42625. }
  42626. }
  42627. // Clip plane
  42628. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42629. // Colors
  42630. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42631. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42632. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42633. }
  42634. if (mustRebind || !this.isFrozen) {
  42635. // Lights
  42636. if (scene.lightsEnabled && !this._disableLighting) {
  42637. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42638. }
  42639. // View
  42640. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42641. this.bindView(effect);
  42642. }
  42643. // Fog
  42644. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42645. // Morph targets
  42646. if (defines.NUM_MORPH_INFLUENCERS) {
  42647. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42648. }
  42649. // Log. depth
  42650. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42651. // image processing
  42652. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42653. this._imageProcessingConfiguration.bind(this._activeEffect);
  42654. }
  42655. }
  42656. this._uniformBuffer.update();
  42657. this._afterBind(mesh, this._activeEffect);
  42658. };
  42659. StandardMaterial.prototype.getAnimatables = function () {
  42660. var results = [];
  42661. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42662. results.push(this._diffuseTexture);
  42663. }
  42664. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42665. results.push(this._ambientTexture);
  42666. }
  42667. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42668. results.push(this._opacityTexture);
  42669. }
  42670. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42671. results.push(this._reflectionTexture);
  42672. }
  42673. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42674. results.push(this._emissiveTexture);
  42675. }
  42676. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42677. results.push(this._specularTexture);
  42678. }
  42679. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42680. results.push(this._bumpTexture);
  42681. }
  42682. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42683. results.push(this._lightmapTexture);
  42684. }
  42685. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42686. results.push(this._refractionTexture);
  42687. }
  42688. return results;
  42689. };
  42690. StandardMaterial.prototype.getActiveTextures = function () {
  42691. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42692. if (this._diffuseTexture) {
  42693. activeTextures.push(this._diffuseTexture);
  42694. }
  42695. if (this._ambientTexture) {
  42696. activeTextures.push(this._ambientTexture);
  42697. }
  42698. if (this._opacityTexture) {
  42699. activeTextures.push(this._opacityTexture);
  42700. }
  42701. if (this._reflectionTexture) {
  42702. activeTextures.push(this._reflectionTexture);
  42703. }
  42704. if (this._emissiveTexture) {
  42705. activeTextures.push(this._emissiveTexture);
  42706. }
  42707. if (this._specularTexture) {
  42708. activeTextures.push(this._specularTexture);
  42709. }
  42710. if (this._bumpTexture) {
  42711. activeTextures.push(this._bumpTexture);
  42712. }
  42713. if (this._lightmapTexture) {
  42714. activeTextures.push(this._lightmapTexture);
  42715. }
  42716. if (this._refractionTexture) {
  42717. activeTextures.push(this._refractionTexture);
  42718. }
  42719. return activeTextures;
  42720. };
  42721. StandardMaterial.prototype.hasTexture = function (texture) {
  42722. if (_super.prototype.hasTexture.call(this, texture)) {
  42723. return true;
  42724. }
  42725. if (this._diffuseTexture === texture) {
  42726. return true;
  42727. }
  42728. if (this._ambientTexture === texture) {
  42729. return true;
  42730. }
  42731. if (this._opacityTexture === texture) {
  42732. return true;
  42733. }
  42734. if (this._reflectionTexture === texture) {
  42735. return true;
  42736. }
  42737. if (this._emissiveTexture === texture) {
  42738. return true;
  42739. }
  42740. if (this._specularTexture === texture) {
  42741. return true;
  42742. }
  42743. if (this._bumpTexture === texture) {
  42744. return true;
  42745. }
  42746. if (this._lightmapTexture === texture) {
  42747. return true;
  42748. }
  42749. if (this._refractionTexture === texture) {
  42750. return true;
  42751. }
  42752. return false;
  42753. };
  42754. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42755. if (forceDisposeTextures) {
  42756. if (this._diffuseTexture) {
  42757. this._diffuseTexture.dispose();
  42758. }
  42759. if (this._ambientTexture) {
  42760. this._ambientTexture.dispose();
  42761. }
  42762. if (this._opacityTexture) {
  42763. this._opacityTexture.dispose();
  42764. }
  42765. if (this._reflectionTexture) {
  42766. this._reflectionTexture.dispose();
  42767. }
  42768. if (this._emissiveTexture) {
  42769. this._emissiveTexture.dispose();
  42770. }
  42771. if (this._specularTexture) {
  42772. this._specularTexture.dispose();
  42773. }
  42774. if (this._bumpTexture) {
  42775. this._bumpTexture.dispose();
  42776. }
  42777. if (this._lightmapTexture) {
  42778. this._lightmapTexture.dispose();
  42779. }
  42780. if (this._refractionTexture) {
  42781. this._refractionTexture.dispose();
  42782. }
  42783. }
  42784. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42785. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42786. }
  42787. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42788. };
  42789. StandardMaterial.prototype.clone = function (name) {
  42790. var _this = this;
  42791. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42792. result.name = name;
  42793. result.id = name;
  42794. return result;
  42795. };
  42796. StandardMaterial.prototype.serialize = function () {
  42797. return BABYLON.SerializationHelper.Serialize(this);
  42798. };
  42799. // Statics
  42800. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42801. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42802. };
  42803. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42804. get: function () {
  42805. return StandardMaterial._DiffuseTextureEnabled;
  42806. },
  42807. set: function (value) {
  42808. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42809. return;
  42810. }
  42811. StandardMaterial._DiffuseTextureEnabled = value;
  42812. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42813. },
  42814. enumerable: true,
  42815. configurable: true
  42816. });
  42817. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42818. get: function () {
  42819. return StandardMaterial._AmbientTextureEnabled;
  42820. },
  42821. set: function (value) {
  42822. if (StandardMaterial._AmbientTextureEnabled === value) {
  42823. return;
  42824. }
  42825. StandardMaterial._AmbientTextureEnabled = value;
  42826. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42827. },
  42828. enumerable: true,
  42829. configurable: true
  42830. });
  42831. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42832. get: function () {
  42833. return StandardMaterial._OpacityTextureEnabled;
  42834. },
  42835. set: function (value) {
  42836. if (StandardMaterial._OpacityTextureEnabled === value) {
  42837. return;
  42838. }
  42839. StandardMaterial._OpacityTextureEnabled = value;
  42840. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42841. },
  42842. enumerable: true,
  42843. configurable: true
  42844. });
  42845. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42846. get: function () {
  42847. return StandardMaterial._ReflectionTextureEnabled;
  42848. },
  42849. set: function (value) {
  42850. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42851. return;
  42852. }
  42853. StandardMaterial._ReflectionTextureEnabled = value;
  42854. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42855. },
  42856. enumerable: true,
  42857. configurable: true
  42858. });
  42859. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42860. get: function () {
  42861. return StandardMaterial._EmissiveTextureEnabled;
  42862. },
  42863. set: function (value) {
  42864. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42865. return;
  42866. }
  42867. StandardMaterial._EmissiveTextureEnabled = value;
  42868. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42869. },
  42870. enumerable: true,
  42871. configurable: true
  42872. });
  42873. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42874. get: function () {
  42875. return StandardMaterial._SpecularTextureEnabled;
  42876. },
  42877. set: function (value) {
  42878. if (StandardMaterial._SpecularTextureEnabled === value) {
  42879. return;
  42880. }
  42881. StandardMaterial._SpecularTextureEnabled = value;
  42882. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42883. },
  42884. enumerable: true,
  42885. configurable: true
  42886. });
  42887. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42888. get: function () {
  42889. return StandardMaterial._BumpTextureEnabled;
  42890. },
  42891. set: function (value) {
  42892. if (StandardMaterial._BumpTextureEnabled === value) {
  42893. return;
  42894. }
  42895. StandardMaterial._BumpTextureEnabled = value;
  42896. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42897. },
  42898. enumerable: true,
  42899. configurable: true
  42900. });
  42901. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42902. get: function () {
  42903. return StandardMaterial._LightmapTextureEnabled;
  42904. },
  42905. set: function (value) {
  42906. if (StandardMaterial._LightmapTextureEnabled === value) {
  42907. return;
  42908. }
  42909. StandardMaterial._LightmapTextureEnabled = value;
  42910. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42911. },
  42912. enumerable: true,
  42913. configurable: true
  42914. });
  42915. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42916. get: function () {
  42917. return StandardMaterial._RefractionTextureEnabled;
  42918. },
  42919. set: function (value) {
  42920. if (StandardMaterial._RefractionTextureEnabled === value) {
  42921. return;
  42922. }
  42923. StandardMaterial._RefractionTextureEnabled = value;
  42924. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42925. },
  42926. enumerable: true,
  42927. configurable: true
  42928. });
  42929. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42930. get: function () {
  42931. return StandardMaterial._ColorGradingTextureEnabled;
  42932. },
  42933. set: function (value) {
  42934. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42935. return;
  42936. }
  42937. StandardMaterial._ColorGradingTextureEnabled = value;
  42938. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42939. },
  42940. enumerable: true,
  42941. configurable: true
  42942. });
  42943. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42944. get: function () {
  42945. return StandardMaterial._FresnelEnabled;
  42946. },
  42947. set: function (value) {
  42948. if (StandardMaterial._FresnelEnabled === value) {
  42949. return;
  42950. }
  42951. StandardMaterial._FresnelEnabled = value;
  42952. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42953. },
  42954. enumerable: true,
  42955. configurable: true
  42956. });
  42957. // Flags used to enable or disable a type of texture for all Standard Materials
  42958. StandardMaterial._DiffuseTextureEnabled = true;
  42959. StandardMaterial._AmbientTextureEnabled = true;
  42960. StandardMaterial._OpacityTextureEnabled = true;
  42961. StandardMaterial._ReflectionTextureEnabled = true;
  42962. StandardMaterial._EmissiveTextureEnabled = true;
  42963. StandardMaterial._SpecularTextureEnabled = true;
  42964. StandardMaterial._BumpTextureEnabled = true;
  42965. StandardMaterial._LightmapTextureEnabled = true;
  42966. StandardMaterial._RefractionTextureEnabled = true;
  42967. StandardMaterial._ColorGradingTextureEnabled = true;
  42968. StandardMaterial._FresnelEnabled = true;
  42969. __decorate([
  42970. BABYLON.serializeAsTexture("diffuseTexture")
  42971. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42972. __decorate([
  42973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42974. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42975. __decorate([
  42976. BABYLON.serializeAsTexture("ambientTexture")
  42977. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42978. __decorate([
  42979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42980. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42981. __decorate([
  42982. BABYLON.serializeAsTexture("opacityTexture")
  42983. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42984. __decorate([
  42985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42986. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42987. __decorate([
  42988. BABYLON.serializeAsTexture("reflectionTexture")
  42989. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42990. __decorate([
  42991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42992. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42993. __decorate([
  42994. BABYLON.serializeAsTexture("emissiveTexture")
  42995. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42996. __decorate([
  42997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42998. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42999. __decorate([
  43000. BABYLON.serializeAsTexture("specularTexture")
  43001. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43002. __decorate([
  43003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43004. ], StandardMaterial.prototype, "specularTexture", void 0);
  43005. __decorate([
  43006. BABYLON.serializeAsTexture("bumpTexture")
  43007. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43008. __decorate([
  43009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43010. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43011. __decorate([
  43012. BABYLON.serializeAsTexture("lightmapTexture")
  43013. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43014. __decorate([
  43015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43016. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43017. __decorate([
  43018. BABYLON.serializeAsTexture("refractionTexture")
  43019. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43020. __decorate([
  43021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43022. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43023. __decorate([
  43024. BABYLON.serializeAsColor3("ambient")
  43025. ], StandardMaterial.prototype, "ambientColor", void 0);
  43026. __decorate([
  43027. BABYLON.serializeAsColor3("diffuse")
  43028. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43029. __decorate([
  43030. BABYLON.serializeAsColor3("specular")
  43031. ], StandardMaterial.prototype, "specularColor", void 0);
  43032. __decorate([
  43033. BABYLON.serializeAsColor3("emissive")
  43034. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43035. __decorate([
  43036. BABYLON.serialize()
  43037. ], StandardMaterial.prototype, "specularPower", void 0);
  43038. __decorate([
  43039. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43040. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43041. __decorate([
  43042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43043. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43044. __decorate([
  43045. BABYLON.serialize("useEmissiveAsIllumination")
  43046. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43047. __decorate([
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43049. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43050. __decorate([
  43051. BABYLON.serialize("linkEmissiveWithDiffuse")
  43052. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43053. __decorate([
  43054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43055. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43056. __decorate([
  43057. BABYLON.serialize("useSpecularOverAlpha")
  43058. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43059. __decorate([
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43062. __decorate([
  43063. BABYLON.serialize("useReflectionOverAlpha")
  43064. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43065. __decorate([
  43066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43067. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43068. __decorate([
  43069. BABYLON.serialize("disableLighting")
  43070. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43071. __decorate([
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43073. ], StandardMaterial.prototype, "disableLighting", void 0);
  43074. __decorate([
  43075. BABYLON.serialize("useObjectSpaceNormalMap")
  43076. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43077. __decorate([
  43078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43079. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43080. __decorate([
  43081. BABYLON.serialize("useParallax")
  43082. ], StandardMaterial.prototype, "_useParallax", void 0);
  43083. __decorate([
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], StandardMaterial.prototype, "useParallax", void 0);
  43086. __decorate([
  43087. BABYLON.serialize("useParallaxOcclusion")
  43088. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43089. __decorate([
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43091. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43092. __decorate([
  43093. BABYLON.serialize()
  43094. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43095. __decorate([
  43096. BABYLON.serialize("roughness")
  43097. ], StandardMaterial.prototype, "_roughness", void 0);
  43098. __decorate([
  43099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43100. ], StandardMaterial.prototype, "roughness", void 0);
  43101. __decorate([
  43102. BABYLON.serialize()
  43103. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43104. __decorate([
  43105. BABYLON.serialize()
  43106. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43107. __decorate([
  43108. BABYLON.serialize()
  43109. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43110. __decorate([
  43111. BABYLON.serialize("useLightmapAsShadowmap")
  43112. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43113. __decorate([
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43116. __decorate([
  43117. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43118. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43119. __decorate([
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43121. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43124. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43125. __decorate([
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43127. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43128. __decorate([
  43129. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43130. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43131. __decorate([
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43133. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43134. __decorate([
  43135. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43136. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43137. __decorate([
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43139. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43140. __decorate([
  43141. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43142. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43143. __decorate([
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43145. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43146. __decorate([
  43147. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43148. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43149. __decorate([
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43151. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43152. __decorate([
  43153. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43154. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43155. __decorate([
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43158. __decorate([
  43159. BABYLON.serialize("maxSimultaneousLights")
  43160. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43161. __decorate([
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43163. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43164. __decorate([
  43165. BABYLON.serialize("invertNormalMapX")
  43166. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43167. __decorate([
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43170. __decorate([
  43171. BABYLON.serialize("invertNormalMapY")
  43172. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43173. __decorate([
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43175. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43176. __decorate([
  43177. BABYLON.serialize("twoSidedLighting")
  43178. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43182. __decorate([
  43183. BABYLON.serialize()
  43184. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43185. return StandardMaterial;
  43186. }(BABYLON.PushMaterial));
  43187. BABYLON.StandardMaterial = StandardMaterial;
  43188. })(BABYLON || (BABYLON = {}));
  43189. //# sourceMappingURL=babylon.standardMaterial.js.map
  43190. var BABYLON;
  43191. (function (BABYLON) {
  43192. /**
  43193. * Class representing spherical polynomial coefficients to the 3rd degree
  43194. */
  43195. var SphericalPolynomial = /** @class */ (function () {
  43196. function SphericalPolynomial() {
  43197. /**
  43198. * The x coefficients of the spherical polynomial
  43199. */
  43200. this.x = BABYLON.Vector3.Zero();
  43201. /**
  43202. * The y coefficients of the spherical polynomial
  43203. */
  43204. this.y = BABYLON.Vector3.Zero();
  43205. /**
  43206. * The z coefficients of the spherical polynomial
  43207. */
  43208. this.z = BABYLON.Vector3.Zero();
  43209. /**
  43210. * The xx coefficients of the spherical polynomial
  43211. */
  43212. this.xx = BABYLON.Vector3.Zero();
  43213. /**
  43214. * The yy coefficients of the spherical polynomial
  43215. */
  43216. this.yy = BABYLON.Vector3.Zero();
  43217. /**
  43218. * The zz coefficients of the spherical polynomial
  43219. */
  43220. this.zz = BABYLON.Vector3.Zero();
  43221. /**
  43222. * The xy coefficients of the spherical polynomial
  43223. */
  43224. this.xy = BABYLON.Vector3.Zero();
  43225. /**
  43226. * The yz coefficients of the spherical polynomial
  43227. */
  43228. this.yz = BABYLON.Vector3.Zero();
  43229. /**
  43230. * The zx coefficients of the spherical polynomial
  43231. */
  43232. this.zx = BABYLON.Vector3.Zero();
  43233. }
  43234. /**
  43235. * Adds an ambient color to the spherical polynomial
  43236. * @param color the color to add
  43237. */
  43238. SphericalPolynomial.prototype.addAmbient = function (color) {
  43239. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43240. this.xx = this.xx.add(colorVector);
  43241. this.yy = this.yy.add(colorVector);
  43242. this.zz = this.zz.add(colorVector);
  43243. };
  43244. /**
  43245. * Scales the spherical polynomial by the given amount
  43246. * @param scale the amount to scale
  43247. */
  43248. SphericalPolynomial.prototype.scale = function (scale) {
  43249. this.x = this.x.scale(scale);
  43250. this.y = this.y.scale(scale);
  43251. this.z = this.z.scale(scale);
  43252. this.xx = this.xx.scale(scale);
  43253. this.yy = this.yy.scale(scale);
  43254. this.zz = this.zz.scale(scale);
  43255. this.yz = this.yz.scale(scale);
  43256. this.zx = this.zx.scale(scale);
  43257. this.xy = this.xy.scale(scale);
  43258. };
  43259. /**
  43260. * Gets the spherical polynomial from harmonics
  43261. * @param harmonics the spherical harmonics
  43262. * @returns the spherical polynomial
  43263. */
  43264. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43265. var result = new SphericalPolynomial();
  43266. result.x = harmonics.l11.scale(1.02333);
  43267. result.y = harmonics.l1_1.scale(1.02333);
  43268. result.z = harmonics.l10.scale(1.02333);
  43269. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43270. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43271. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43272. result.yz = harmonics.l2_1.scale(0.858086);
  43273. result.zx = harmonics.l21.scale(0.858086);
  43274. result.xy = harmonics.l2_2.scale(0.858086);
  43275. result.scale(1.0 / Math.PI);
  43276. return result;
  43277. };
  43278. /**
  43279. * Constructs a spherical polynomial from an array.
  43280. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43281. * @returns the spherical polynomial
  43282. */
  43283. SphericalPolynomial.FromArray = function (data) {
  43284. var sp = new SphericalPolynomial();
  43285. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43286. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43287. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43288. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43289. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43290. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43291. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43292. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43293. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43294. return sp;
  43295. };
  43296. return SphericalPolynomial;
  43297. }());
  43298. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43299. /**
  43300. * Class representing spherical harmonics coefficients to the 3rd degree
  43301. */
  43302. var SphericalHarmonics = /** @class */ (function () {
  43303. function SphericalHarmonics() {
  43304. /**
  43305. * The l0,0 coefficients of the spherical harmonics
  43306. */
  43307. this.l00 = BABYLON.Vector3.Zero();
  43308. /**
  43309. * The l1,-1 coefficients of the spherical harmonics
  43310. */
  43311. this.l1_1 = BABYLON.Vector3.Zero();
  43312. /**
  43313. * The l1,0 coefficients of the spherical harmonics
  43314. */
  43315. this.l10 = BABYLON.Vector3.Zero();
  43316. /**
  43317. * The l1,1 coefficients of the spherical harmonics
  43318. */
  43319. this.l11 = BABYLON.Vector3.Zero();
  43320. /**
  43321. * The l2,-2 coefficients of the spherical harmonics
  43322. */
  43323. this.l2_2 = BABYLON.Vector3.Zero();
  43324. /**
  43325. * The l2,-1 coefficients of the spherical harmonics
  43326. */
  43327. this.l2_1 = BABYLON.Vector3.Zero();
  43328. /**
  43329. * The l2,0 coefficients of the spherical harmonics
  43330. */
  43331. this.l20 = BABYLON.Vector3.Zero();
  43332. /**
  43333. * The l2,1 coefficients of the spherical harmonics
  43334. */
  43335. this.l21 = BABYLON.Vector3.Zero();
  43336. /**
  43337. * The l2,2 coefficients of the spherical harmonics
  43338. */
  43339. this.lL22 = BABYLON.Vector3.Zero();
  43340. }
  43341. /**
  43342. * Adds a light to the spherical harmonics
  43343. * @param direction the direction of the light
  43344. * @param color the color of the light
  43345. * @param deltaSolidAngle the delta solid angle of the light
  43346. */
  43347. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43348. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43349. var c = colorVector.scale(deltaSolidAngle);
  43350. this.l00 = this.l00.add(c.scale(0.282095));
  43351. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43352. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43353. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43354. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43355. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43356. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43357. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43358. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43359. };
  43360. /**
  43361. * Scales the spherical harmonics by the given amount
  43362. * @param scale the amount to scale
  43363. */
  43364. SphericalHarmonics.prototype.scale = function (scale) {
  43365. this.l00 = this.l00.scale(scale);
  43366. this.l1_1 = this.l1_1.scale(scale);
  43367. this.l10 = this.l10.scale(scale);
  43368. this.l11 = this.l11.scale(scale);
  43369. this.l2_2 = this.l2_2.scale(scale);
  43370. this.l2_1 = this.l2_1.scale(scale);
  43371. this.l20 = this.l20.scale(scale);
  43372. this.l21 = this.l21.scale(scale);
  43373. this.lL22 = this.lL22.scale(scale);
  43374. };
  43375. /**
  43376. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43377. *
  43378. * ```
  43379. * E_lm = A_l * L_lm
  43380. * ```
  43381. *
  43382. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43383. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43384. * the scaling factors are given in equation 9.
  43385. */
  43386. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43387. // Constant (Band 0)
  43388. this.l00 = this.l00.scale(3.141593);
  43389. // Linear (Band 1)
  43390. this.l1_1 = this.l1_1.scale(2.094395);
  43391. this.l10 = this.l10.scale(2.094395);
  43392. this.l11 = this.l11.scale(2.094395);
  43393. // Quadratic (Band 2)
  43394. this.l2_2 = this.l2_2.scale(0.785398);
  43395. this.l2_1 = this.l2_1.scale(0.785398);
  43396. this.l20 = this.l20.scale(0.785398);
  43397. this.l21 = this.l21.scale(0.785398);
  43398. this.lL22 = this.lL22.scale(0.785398);
  43399. };
  43400. /**
  43401. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43402. *
  43403. * ```
  43404. * L = (1/pi) * E * rho
  43405. * ```
  43406. *
  43407. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43408. */
  43409. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43410. this.scale(1.0 / Math.PI);
  43411. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43412. // (The pixel shader must apply albedo after texture fetches, etc).
  43413. };
  43414. /**
  43415. * Gets the spherical harmonics from polynomial
  43416. * @param polynomial the spherical polynomial
  43417. * @returns the spherical harmonics
  43418. */
  43419. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43420. var result = new SphericalHarmonics();
  43421. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43422. result.l1_1 = polynomial.y.scale(0.977204);
  43423. result.l10 = polynomial.z.scale(0.977204);
  43424. result.l11 = polynomial.x.scale(0.977204);
  43425. result.l2_2 = polynomial.xy.scale(1.16538);
  43426. result.l2_1 = polynomial.yz.scale(1.16538);
  43427. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43428. result.l21 = polynomial.zx.scale(1.16538);
  43429. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43430. result.scale(Math.PI);
  43431. return result;
  43432. };
  43433. /**
  43434. * Constructs a spherical harmonics from an array.
  43435. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43436. * @returns the spherical harmonics
  43437. */
  43438. SphericalHarmonics.FromArray = function (data) {
  43439. var sh = new SphericalHarmonics();
  43440. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43441. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43442. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43443. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43444. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43445. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43446. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43447. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43448. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43449. return sh;
  43450. };
  43451. return SphericalHarmonics;
  43452. }());
  43453. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43454. })(BABYLON || (BABYLON = {}));
  43455. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43456. var BABYLON;
  43457. (function (BABYLON) {
  43458. var FileFaceOrientation = /** @class */ (function () {
  43459. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43460. this.name = name;
  43461. this.worldAxisForNormal = worldAxisForNormal;
  43462. this.worldAxisForFileX = worldAxisForFileX;
  43463. this.worldAxisForFileY = worldAxisForFileY;
  43464. }
  43465. return FileFaceOrientation;
  43466. }());
  43467. ;
  43468. /**
  43469. * Helper class dealing with the extraction of spherical polynomial dataArray
  43470. * from a cube map.
  43471. */
  43472. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43473. function CubeMapToSphericalPolynomialTools() {
  43474. }
  43475. /**
  43476. * Converts a texture to the according Spherical Polynomial data.
  43477. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43478. *
  43479. * @param texture The texture to extract the information from.
  43480. * @return The Spherical Polynomial data.
  43481. */
  43482. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43483. if (!texture.isCube) {
  43484. // Only supports cube Textures currently.
  43485. return null;
  43486. }
  43487. var size = texture.getSize().width;
  43488. var right = texture.readPixels(0);
  43489. var left = texture.readPixels(1);
  43490. var up;
  43491. var down;
  43492. if (texture.isRenderTarget) {
  43493. up = texture.readPixels(3);
  43494. down = texture.readPixels(2);
  43495. }
  43496. else {
  43497. up = texture.readPixels(2);
  43498. down = texture.readPixels(3);
  43499. }
  43500. var front = texture.readPixels(4);
  43501. var back = texture.readPixels(5);
  43502. var gammaSpace = texture.gammaSpace;
  43503. // Always read as RGBA.
  43504. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43505. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43506. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43507. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43508. }
  43509. var cubeInfo = {
  43510. size: size,
  43511. right: right,
  43512. left: left,
  43513. up: up,
  43514. down: down,
  43515. front: front,
  43516. back: back,
  43517. format: format,
  43518. type: type,
  43519. gammaSpace: gammaSpace,
  43520. };
  43521. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43522. };
  43523. /**
  43524. * Converts a cubemap to the according Spherical Polynomial data.
  43525. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43526. *
  43527. * @param cubeInfo The Cube map to extract the information from.
  43528. * @return The Spherical Polynomial data.
  43529. */
  43530. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43531. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43532. var totalSolidAngle = 0.0;
  43533. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43534. var du = 2.0 / cubeInfo.size;
  43535. var dv = du;
  43536. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43537. var minUV = du * 0.5 - 1.0;
  43538. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43539. var fileFace = this.FileFaces[faceIndex];
  43540. var dataArray = cubeInfo[fileFace.name];
  43541. var v = minUV;
  43542. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43543. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43544. // Because SP is still linear, so summation is fine in that basis.
  43545. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43546. for (var y = 0; y < cubeInfo.size; y++) {
  43547. var u = minUV;
  43548. for (var x = 0; x < cubeInfo.size; x++) {
  43549. // World direction (not normalised)
  43550. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43551. worldDirection.normalize();
  43552. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43553. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43554. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43555. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43556. // Handle Integer types.
  43557. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43558. r /= 255;
  43559. g /= 255;
  43560. b /= 255;
  43561. }
  43562. // Handle Gamma space textures.
  43563. if (cubeInfo.gammaSpace) {
  43564. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43565. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43566. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43567. }
  43568. var color = new BABYLON.Color3(r, g, b);
  43569. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43570. totalSolidAngle += deltaSolidAngle;
  43571. u += du;
  43572. }
  43573. v += dv;
  43574. }
  43575. }
  43576. // Solid angle for entire sphere is 4*pi
  43577. var sphereSolidAngle = 4.0 * Math.PI;
  43578. // Adjust the solid angle to allow for how many faces we processed.
  43579. var facesProcessed = 6.0;
  43580. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43581. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43582. // This is needed because the numerical integration over the cube uses a
  43583. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43584. // and also to compensate for accumulative error due to float precision in the summation.
  43585. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43586. sphericalHarmonics.scale(correctionFactor);
  43587. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43588. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43589. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43590. };
  43591. CubeMapToSphericalPolynomialTools.FileFaces = [
  43592. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43593. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43594. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43595. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43596. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43597. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43598. ];
  43599. return CubeMapToSphericalPolynomialTools;
  43600. }());
  43601. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43602. })(BABYLON || (BABYLON = {}));
  43603. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43604. var BABYLON;
  43605. (function (BABYLON) {
  43606. /**
  43607. * Manages the defines for the PBR Material.
  43608. * @hiddenChildren
  43609. */
  43610. var PBRMaterialDefines = /** @class */ (function (_super) {
  43611. __extends(PBRMaterialDefines, _super);
  43612. /**
  43613. * Initializes the PBR Material defines.
  43614. */
  43615. function PBRMaterialDefines() {
  43616. var _this = _super.call(this) || this;
  43617. _this.PBR = true;
  43618. _this.MAINUV1 = false;
  43619. _this.MAINUV2 = false;
  43620. _this.UV1 = false;
  43621. _this.UV2 = false;
  43622. _this.ALBEDO = false;
  43623. _this.ALBEDODIRECTUV = 0;
  43624. _this.VERTEXCOLOR = false;
  43625. _this.AMBIENT = false;
  43626. _this.AMBIENTDIRECTUV = 0;
  43627. _this.AMBIENTINGRAYSCALE = false;
  43628. _this.OPACITY = false;
  43629. _this.VERTEXALPHA = false;
  43630. _this.OPACITYDIRECTUV = 0;
  43631. _this.OPACITYRGB = false;
  43632. _this.ALPHATEST = false;
  43633. _this.DEPTHPREPASS = false;
  43634. _this.ALPHABLEND = false;
  43635. _this.ALPHAFROMALBEDO = false;
  43636. _this.ALPHATESTVALUE = "0.5";
  43637. _this.SPECULAROVERALPHA = false;
  43638. _this.RADIANCEOVERALPHA = false;
  43639. _this.ALPHAFRESNEL = false;
  43640. _this.LINEARALPHAFRESNEL = false;
  43641. _this.PREMULTIPLYALPHA = false;
  43642. _this.EMISSIVE = false;
  43643. _this.EMISSIVEDIRECTUV = 0;
  43644. _this.REFLECTIVITY = false;
  43645. _this.REFLECTIVITYDIRECTUV = 0;
  43646. _this.SPECULARTERM = false;
  43647. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43648. _this.MICROSURFACEAUTOMATIC = false;
  43649. _this.LODBASEDMICROSFURACE = false;
  43650. _this.MICROSURFACEMAP = false;
  43651. _this.MICROSURFACEMAPDIRECTUV = 0;
  43652. _this.METALLICWORKFLOW = false;
  43653. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43654. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43655. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43656. _this.AOSTOREINMETALMAPRED = false;
  43657. _this.ENVIRONMENTBRDF = false;
  43658. _this.NORMAL = false;
  43659. _this.TANGENT = false;
  43660. _this.BUMP = false;
  43661. _this.BUMPDIRECTUV = 0;
  43662. _this.OBJECTSPACE_NORMALMAP = false;
  43663. _this.PARALLAX = false;
  43664. _this.PARALLAXOCCLUSION = false;
  43665. _this.NORMALXYSCALE = true;
  43666. _this.LIGHTMAP = false;
  43667. _this.LIGHTMAPDIRECTUV = 0;
  43668. _this.USELIGHTMAPASSHADOWMAP = false;
  43669. _this.GAMMALIGHTMAP = false;
  43670. _this.REFLECTION = false;
  43671. _this.REFLECTIONMAP_3D = false;
  43672. _this.REFLECTIONMAP_SPHERICAL = false;
  43673. _this.REFLECTIONMAP_PLANAR = false;
  43674. _this.REFLECTIONMAP_CUBIC = false;
  43675. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43676. _this.REFLECTIONMAP_PROJECTION = false;
  43677. _this.REFLECTIONMAP_SKYBOX = false;
  43678. _this.REFLECTIONMAP_EXPLICIT = false;
  43679. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43680. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43681. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43682. _this.INVERTCUBICMAP = false;
  43683. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43684. _this.USESPHERICALINVERTEX = false;
  43685. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43686. _this.LODINREFLECTIONALPHA = false;
  43687. _this.GAMMAREFLECTION = false;
  43688. _this.RGBDREFLECTION = false;
  43689. _this.RADIANCEOCCLUSION = false;
  43690. _this.HORIZONOCCLUSION = false;
  43691. _this.REFRACTION = false;
  43692. _this.REFRACTIONMAP_3D = false;
  43693. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43694. _this.LODINREFRACTIONALPHA = false;
  43695. _this.GAMMAREFRACTION = false;
  43696. _this.RGBDREFRACTION = false;
  43697. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43698. _this.INSTANCES = false;
  43699. _this.NUM_BONE_INFLUENCERS = 0;
  43700. _this.BonesPerMesh = 0;
  43701. _this.NONUNIFORMSCALING = false;
  43702. _this.MORPHTARGETS = false;
  43703. _this.MORPHTARGETS_NORMAL = false;
  43704. _this.MORPHTARGETS_TANGENT = false;
  43705. _this.NUM_MORPH_INFLUENCERS = 0;
  43706. _this.IMAGEPROCESSING = false;
  43707. _this.VIGNETTE = false;
  43708. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43709. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43710. _this.TONEMAPPING = false;
  43711. _this.TONEMAPPING_ACES = false;
  43712. _this.CONTRAST = false;
  43713. _this.COLORCURVES = false;
  43714. _this.COLORGRADING = false;
  43715. _this.COLORGRADING3D = false;
  43716. _this.SAMPLER3DGREENDEPTH = false;
  43717. _this.SAMPLER3DBGRMAP = false;
  43718. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43719. _this.EXPOSURE = false;
  43720. _this.USEPHYSICALLIGHTFALLOFF = false;
  43721. _this.USEGLTFLIGHTFALLOFF = false;
  43722. _this.TWOSIDEDLIGHTING = false;
  43723. _this.SHADOWFLOAT = false;
  43724. _this.CLIPPLANE = false;
  43725. _this.CLIPPLANE2 = false;
  43726. _this.CLIPPLANE3 = false;
  43727. _this.CLIPPLANE4 = false;
  43728. _this.POINTSIZE = false;
  43729. _this.FOG = false;
  43730. _this.LOGARITHMICDEPTH = false;
  43731. _this.FORCENORMALFORWARD = false;
  43732. _this.SPECULARAA = false;
  43733. _this.UNLIT = false;
  43734. _this.rebuild();
  43735. return _this;
  43736. }
  43737. /**
  43738. * Resets the PBR Material defines.
  43739. */
  43740. PBRMaterialDefines.prototype.reset = function () {
  43741. _super.prototype.reset.call(this);
  43742. this.ALPHATESTVALUE = "0.5";
  43743. this.PBR = true;
  43744. };
  43745. return PBRMaterialDefines;
  43746. }(BABYLON.MaterialDefines));
  43747. /**
  43748. * The Physically based material base class of BJS.
  43749. *
  43750. * This offers the main features of a standard PBR material.
  43751. * For more information, please refer to the documentation :
  43752. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43753. */
  43754. var PBRBaseMaterial = /** @class */ (function (_super) {
  43755. __extends(PBRBaseMaterial, _super);
  43756. /**
  43757. * Instantiates a new PBRMaterial instance.
  43758. *
  43759. * @param name The material name
  43760. * @param scene The scene the material will be use in.
  43761. */
  43762. function PBRBaseMaterial(name, scene) {
  43763. var _this = _super.call(this, name, scene) || this;
  43764. /**
  43765. * Intensity of the direct lights e.g. the four lights available in your scene.
  43766. * This impacts both the direct diffuse and specular highlights.
  43767. */
  43768. _this._directIntensity = 1.0;
  43769. /**
  43770. * Intensity of the emissive part of the material.
  43771. * This helps controlling the emissive effect without modifying the emissive color.
  43772. */
  43773. _this._emissiveIntensity = 1.0;
  43774. /**
  43775. * Intensity of the environment e.g. how much the environment will light the object
  43776. * either through harmonics for rough material or through the refelction for shiny ones.
  43777. */
  43778. _this._environmentIntensity = 1.0;
  43779. /**
  43780. * This is a special control allowing the reduction of the specular highlights coming from the
  43781. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43782. */
  43783. _this._specularIntensity = 1.0;
  43784. /**
  43785. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43786. */
  43787. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43788. /**
  43789. * Debug Control allowing disabling the bump map on this material.
  43790. */
  43791. _this._disableBumpMap = false;
  43792. /**
  43793. * AKA Occlusion Texture Intensity in other nomenclature.
  43794. */
  43795. _this._ambientTextureStrength = 1.0;
  43796. /**
  43797. * The color of a material in ambient lighting.
  43798. */
  43799. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43800. /**
  43801. * AKA Diffuse Color in other nomenclature.
  43802. */
  43803. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43804. /**
  43805. * AKA Specular Color in other nomenclature.
  43806. */
  43807. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43808. /**
  43809. * The color applied when light is reflected from a material.
  43810. */
  43811. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43812. /**
  43813. * The color applied when light is emitted from a material.
  43814. */
  43815. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43816. /**
  43817. * AKA Glossiness in other nomenclature.
  43818. */
  43819. _this._microSurface = 0.9;
  43820. /**
  43821. * source material index of refraction (IOR)' / 'destination material IOR.
  43822. */
  43823. _this._indexOfRefraction = 0.66;
  43824. /**
  43825. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43826. */
  43827. _this._invertRefractionY = false;
  43828. /**
  43829. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43830. * Materials half opaque for instance using refraction could benefit from this control.
  43831. */
  43832. _this._linkRefractionWithTransparency = false;
  43833. /**
  43834. * Specifies that the material will use the light map as a show map.
  43835. */
  43836. _this._useLightmapAsShadowmap = false;
  43837. /**
  43838. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43839. * makes the reflect vector face the model (under horizon).
  43840. */
  43841. _this._useHorizonOcclusion = true;
  43842. /**
  43843. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43844. * too much the area relying on ambient texture to define their ambient occlusion.
  43845. */
  43846. _this._useRadianceOcclusion = true;
  43847. /**
  43848. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43849. */
  43850. _this._useAlphaFromAlbedoTexture = false;
  43851. /**
  43852. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43853. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43854. */
  43855. _this._useSpecularOverAlpha = true;
  43856. /**
  43857. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43858. */
  43859. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43860. /**
  43861. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43862. */
  43863. _this._useRoughnessFromMetallicTextureAlpha = true;
  43864. /**
  43865. * Specifies if the metallic texture contains the roughness information in its green channel.
  43866. */
  43867. _this._useRoughnessFromMetallicTextureGreen = false;
  43868. /**
  43869. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43870. */
  43871. _this._useMetallnessFromMetallicTextureBlue = false;
  43872. /**
  43873. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43874. */
  43875. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43876. /**
  43877. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43878. */
  43879. _this._useAmbientInGrayScale = false;
  43880. /**
  43881. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43882. * The material will try to infer what glossiness each pixel should be.
  43883. */
  43884. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43885. /**
  43886. * Defines the falloff type used in this material.
  43887. * It by default is Physical.
  43888. */
  43889. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43890. /**
  43891. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43892. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43893. */
  43894. _this._useRadianceOverAlpha = true;
  43895. /**
  43896. * Allows using an object space normal map (instead of tangent space).
  43897. */
  43898. _this._useObjectSpaceNormalMap = false;
  43899. /**
  43900. * Allows using the bump map in parallax mode.
  43901. */
  43902. _this._useParallax = false;
  43903. /**
  43904. * Allows using the bump map in parallax occlusion mode.
  43905. */
  43906. _this._useParallaxOcclusion = false;
  43907. /**
  43908. * Controls the scale bias of the parallax mode.
  43909. */
  43910. _this._parallaxScaleBias = 0.05;
  43911. /**
  43912. * If sets to true, disables all the lights affecting the material.
  43913. */
  43914. _this._disableLighting = false;
  43915. /**
  43916. * Number of Simultaneous lights allowed on the material.
  43917. */
  43918. _this._maxSimultaneousLights = 4;
  43919. /**
  43920. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43921. */
  43922. _this._invertNormalMapX = false;
  43923. /**
  43924. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43925. */
  43926. _this._invertNormalMapY = false;
  43927. /**
  43928. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43929. */
  43930. _this._twoSidedLighting = false;
  43931. /**
  43932. * Defines the alpha limits in alpha test mode.
  43933. */
  43934. _this._alphaCutOff = 0.4;
  43935. /**
  43936. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43937. */
  43938. _this._forceAlphaTest = false;
  43939. /**
  43940. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43941. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43942. */
  43943. _this._useAlphaFresnel = false;
  43944. /**
  43945. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43946. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43947. */
  43948. _this._useLinearAlphaFresnel = false;
  43949. /**
  43950. * The transparency mode of the material.
  43951. */
  43952. _this._transparencyMode = null;
  43953. /**
  43954. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43955. * from cos thetav and roughness:
  43956. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43957. */
  43958. _this._environmentBRDFTexture = null;
  43959. /**
  43960. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43961. */
  43962. _this._forceIrradianceInFragment = false;
  43963. /**
  43964. * Force normal to face away from face.
  43965. */
  43966. _this._forceNormalForward = false;
  43967. /**
  43968. * Enables specular anti aliasing in the PBR shader.
  43969. * It will both interacts on the Geometry for analytical and IBL lighting.
  43970. * It also prefilter the roughness map based on the bump values.
  43971. */
  43972. _this._enableSpecularAntiAliasing = false;
  43973. /**
  43974. * Stores the available render targets.
  43975. */
  43976. _this._renderTargets = new BABYLON.SmartArray(16);
  43977. /**
  43978. * Sets the global ambient color for the material used in lighting calculations.
  43979. */
  43980. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43981. /**
  43982. * If set to true, no lighting calculations will be applied.
  43983. */
  43984. _this._unlit = false;
  43985. // Setup the default processing configuration to the scene.
  43986. _this._attachImageProcessingConfiguration(null);
  43987. _this.getRenderTargetTextures = function () {
  43988. _this._renderTargets.reset();
  43989. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43990. _this._renderTargets.push(_this._reflectionTexture);
  43991. }
  43992. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43993. _this._renderTargets.push(_this._refractionTexture);
  43994. }
  43995. return _this._renderTargets;
  43996. };
  43997. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43998. return _this;
  43999. }
  44000. /**
  44001. * Attaches a new image processing configuration to the PBR Material.
  44002. * @param configuration
  44003. */
  44004. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44005. var _this = this;
  44006. if (configuration === this._imageProcessingConfiguration) {
  44007. return;
  44008. }
  44009. // Detaches observer.
  44010. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44011. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44012. }
  44013. // Pick the scene configuration if needed.
  44014. if (!configuration) {
  44015. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44016. }
  44017. else {
  44018. this._imageProcessingConfiguration = configuration;
  44019. }
  44020. // Attaches observer.
  44021. if (this._imageProcessingConfiguration) {
  44022. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44023. _this._markAllSubMeshesAsImageProcessingDirty();
  44024. });
  44025. }
  44026. };
  44027. /**
  44028. * Gets the name of the material class.
  44029. */
  44030. PBRBaseMaterial.prototype.getClassName = function () {
  44031. return "PBRBaseMaterial";
  44032. };
  44033. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44034. /**
  44035. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44036. */
  44037. get: function () {
  44038. return this._useLogarithmicDepth;
  44039. },
  44040. /**
  44041. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44042. */
  44043. set: function (value) {
  44044. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44045. },
  44046. enumerable: true,
  44047. configurable: true
  44048. });
  44049. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44050. /**
  44051. * Gets the current transparency mode.
  44052. */
  44053. get: function () {
  44054. return this._transparencyMode;
  44055. },
  44056. /**
  44057. * Sets the transparency mode of the material.
  44058. *
  44059. * | Value | Type | Description |
  44060. * | ----- | ----------------------------------- | ----------- |
  44061. * | 0 | OPAQUE | |
  44062. * | 1 | ALPHATEST | |
  44063. * | 2 | ALPHABLEND | |
  44064. * | 3 | ALPHATESTANDBLEND | |
  44065. *
  44066. */
  44067. set: function (value) {
  44068. if (this._transparencyMode === value) {
  44069. return;
  44070. }
  44071. this._transparencyMode = value;
  44072. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44073. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44074. },
  44075. enumerable: true,
  44076. configurable: true
  44077. });
  44078. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44079. /**
  44080. * Returns true if alpha blending should be disabled.
  44081. */
  44082. get: function () {
  44083. return (this._linkRefractionWithTransparency ||
  44084. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44085. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44086. },
  44087. enumerable: true,
  44088. configurable: true
  44089. });
  44090. /**
  44091. * Specifies whether or not this material should be rendered in alpha blend mode.
  44092. */
  44093. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44094. if (this._disableAlphaBlending) {
  44095. return false;
  44096. }
  44097. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44098. };
  44099. /**
  44100. * Specifies if the mesh will require alpha blending.
  44101. * @param mesh - BJS mesh.
  44102. */
  44103. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44104. if (this._disableAlphaBlending) {
  44105. return false;
  44106. }
  44107. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44108. };
  44109. /**
  44110. * Specifies whether or not this material should be rendered in alpha test mode.
  44111. */
  44112. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44113. if (this._forceAlphaTest) {
  44114. return true;
  44115. }
  44116. if (this._linkRefractionWithTransparency) {
  44117. return false;
  44118. }
  44119. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44120. };
  44121. /**
  44122. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44123. */
  44124. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44125. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44126. };
  44127. /**
  44128. * Gets the texture used for the alpha test.
  44129. */
  44130. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44131. return this._albedoTexture;
  44132. };
  44133. /**
  44134. * Specifies that the submesh is ready to be used.
  44135. * @param mesh - BJS mesh.
  44136. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44137. * @param useInstances - Specifies that instances should be used.
  44138. * @returns - boolean indicating that the submesh is ready or not.
  44139. */
  44140. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44141. if (subMesh.effect && this.isFrozen) {
  44142. if (this._wasPreviouslyReady) {
  44143. return true;
  44144. }
  44145. }
  44146. if (!subMesh._materialDefines) {
  44147. subMesh._materialDefines = new PBRMaterialDefines();
  44148. }
  44149. var defines = subMesh._materialDefines;
  44150. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44151. if (defines._renderId === this.getScene().getRenderId()) {
  44152. return true;
  44153. }
  44154. }
  44155. var scene = this.getScene();
  44156. var engine = scene.getEngine();
  44157. if (defines._areTexturesDirty) {
  44158. if (scene.texturesEnabled) {
  44159. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44160. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44161. return false;
  44162. }
  44163. }
  44164. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44165. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44166. return false;
  44167. }
  44168. }
  44169. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44170. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44171. return false;
  44172. }
  44173. }
  44174. var reflectionTexture = this._getReflectionTexture();
  44175. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44176. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44177. return false;
  44178. }
  44179. }
  44180. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44181. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44182. return false;
  44183. }
  44184. }
  44185. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44186. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44187. return false;
  44188. }
  44189. }
  44190. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44191. if (this._metallicTexture) {
  44192. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44193. return false;
  44194. }
  44195. }
  44196. else if (this._reflectivityTexture) {
  44197. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44198. return false;
  44199. }
  44200. }
  44201. if (this._microSurfaceTexture) {
  44202. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44203. return false;
  44204. }
  44205. }
  44206. }
  44207. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44208. // Bump texture cannot be not blocking.
  44209. if (!this._bumpTexture.isReady()) {
  44210. return false;
  44211. }
  44212. }
  44213. var refractionTexture = this._getRefractionTexture();
  44214. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44215. if (!refractionTexture.isReadyOrNotBlocking()) {
  44216. return false;
  44217. }
  44218. }
  44219. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44220. // This is blocking.
  44221. if (!this._environmentBRDFTexture.isReady()) {
  44222. return false;
  44223. }
  44224. }
  44225. }
  44226. }
  44227. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44228. if (!this._imageProcessingConfiguration.isReady()) {
  44229. return false;
  44230. }
  44231. }
  44232. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44233. mesh.createNormals(true);
  44234. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44235. }
  44236. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44237. if (effect) {
  44238. scene.resetCachedMaterial();
  44239. subMesh.setEffect(effect, defines);
  44240. this.buildUniformLayout();
  44241. }
  44242. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44243. return false;
  44244. }
  44245. defines._renderId = scene.getRenderId();
  44246. this._wasPreviouslyReady = true;
  44247. return true;
  44248. };
  44249. /**
  44250. * Specifies if the material uses metallic roughness workflow.
  44251. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44252. */
  44253. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44254. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44255. return true;
  44256. }
  44257. return false;
  44258. };
  44259. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44260. if (onCompiled === void 0) { onCompiled = null; }
  44261. if (onError === void 0) { onError = null; }
  44262. if (useInstances === void 0) { useInstances = null; }
  44263. if (useClipPlane === void 0) { useClipPlane = null; }
  44264. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44265. if (!defines.isDirty) {
  44266. return null;
  44267. }
  44268. defines.markAsProcessed();
  44269. var scene = this.getScene();
  44270. var engine = scene.getEngine();
  44271. // Fallbacks
  44272. var fallbacks = new BABYLON.EffectFallbacks();
  44273. var fallbackRank = 0;
  44274. if (defines.USESPHERICALINVERTEX) {
  44275. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44276. }
  44277. if (defines.FOG) {
  44278. fallbacks.addFallback(fallbackRank, "FOG");
  44279. }
  44280. if (defines.SPECULARAA) {
  44281. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44282. }
  44283. if (defines.POINTSIZE) {
  44284. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44285. }
  44286. if (defines.LOGARITHMICDEPTH) {
  44287. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44288. }
  44289. if (defines.PARALLAX) {
  44290. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44291. }
  44292. if (defines.PARALLAXOCCLUSION) {
  44293. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44294. }
  44295. if (defines.ENVIRONMENTBRDF) {
  44296. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44297. }
  44298. if (defines.TANGENT) {
  44299. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44300. }
  44301. if (defines.BUMP) {
  44302. fallbacks.addFallback(fallbackRank++, "BUMP");
  44303. }
  44304. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44305. if (defines.SPECULARTERM) {
  44306. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44307. }
  44308. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44309. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44310. }
  44311. if (defines.LIGHTMAP) {
  44312. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44313. }
  44314. if (defines.NORMAL) {
  44315. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44316. }
  44317. if (defines.AMBIENT) {
  44318. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44319. }
  44320. if (defines.EMISSIVE) {
  44321. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44322. }
  44323. if (defines.VERTEXCOLOR) {
  44324. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44325. }
  44326. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44327. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44328. }
  44329. if (defines.MORPHTARGETS) {
  44330. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44331. }
  44332. //Attributes
  44333. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44334. if (defines.NORMAL) {
  44335. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44336. }
  44337. if (defines.TANGENT) {
  44338. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44339. }
  44340. if (defines.UV1) {
  44341. attribs.push(BABYLON.VertexBuffer.UVKind);
  44342. }
  44343. if (defines.UV2) {
  44344. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44345. }
  44346. if (defines.VERTEXCOLOR) {
  44347. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44348. }
  44349. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44350. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44351. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44352. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44353. "vFogInfos", "vFogColor", "pointSize",
  44354. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44355. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44356. "mBones",
  44357. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44358. "vLightingIntensity",
  44359. "logarithmicDepthConstant",
  44360. "vSphericalX", "vSphericalY", "vSphericalZ",
  44361. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44362. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44363. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44364. "vTangentSpaceParams"
  44365. ];
  44366. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44367. "bumpSampler", "lightmapSampler", "opacitySampler",
  44368. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44369. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44370. "microSurfaceSampler", "environmentBrdfSampler"];
  44371. var uniformBuffers = ["Material", "Scene"];
  44372. if (BABYLON.ImageProcessingConfiguration) {
  44373. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44374. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44375. }
  44376. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44377. uniformsNames: uniforms,
  44378. uniformBuffersNames: uniformBuffers,
  44379. samplers: samplers,
  44380. defines: defines,
  44381. maxSimultaneousLights: this._maxSimultaneousLights
  44382. });
  44383. var join = defines.toString();
  44384. return engine.createEffect("pbr", {
  44385. attributes: attribs,
  44386. uniformsNames: uniforms,
  44387. uniformBuffersNames: uniformBuffers,
  44388. samplers: samplers,
  44389. defines: join,
  44390. fallbacks: fallbacks,
  44391. onCompiled: onCompiled,
  44392. onError: onError,
  44393. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44394. }, engine);
  44395. };
  44396. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44397. if (useInstances === void 0) { useInstances = null; }
  44398. if (useClipPlane === void 0) { useClipPlane = null; }
  44399. var scene = this.getScene();
  44400. var engine = scene.getEngine();
  44401. // Lights
  44402. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44403. defines._needNormals = true;
  44404. // Textures
  44405. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44406. if (defines._areTexturesDirty) {
  44407. defines._needUVs = false;
  44408. if (scene.texturesEnabled) {
  44409. if (scene.getEngine().getCaps().textureLOD) {
  44410. defines.LODBASEDMICROSFURACE = true;
  44411. }
  44412. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44413. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44414. }
  44415. else {
  44416. defines.ALBEDO = false;
  44417. }
  44418. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44419. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44420. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44421. }
  44422. else {
  44423. defines.AMBIENT = false;
  44424. }
  44425. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44426. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44427. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44428. }
  44429. else {
  44430. defines.OPACITY = false;
  44431. }
  44432. var reflectionTexture = this._getReflectionTexture();
  44433. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44434. defines.REFLECTION = true;
  44435. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44436. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44437. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44438. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44439. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44440. defines.INVERTCUBICMAP = true;
  44441. }
  44442. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44443. switch (reflectionTexture.coordinatesMode) {
  44444. case BABYLON.Texture.EXPLICIT_MODE:
  44445. defines.REFLECTIONMAP_EXPLICIT = true;
  44446. break;
  44447. case BABYLON.Texture.PLANAR_MODE:
  44448. defines.REFLECTIONMAP_PLANAR = true;
  44449. break;
  44450. case BABYLON.Texture.PROJECTION_MODE:
  44451. defines.REFLECTIONMAP_PROJECTION = true;
  44452. break;
  44453. case BABYLON.Texture.SKYBOX_MODE:
  44454. defines.REFLECTIONMAP_SKYBOX = true;
  44455. break;
  44456. case BABYLON.Texture.SPHERICAL_MODE:
  44457. defines.REFLECTIONMAP_SPHERICAL = true;
  44458. break;
  44459. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44460. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44461. break;
  44462. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44463. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44464. break;
  44465. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44466. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44467. break;
  44468. case BABYLON.Texture.CUBIC_MODE:
  44469. case BABYLON.Texture.INVCUBIC_MODE:
  44470. default:
  44471. defines.REFLECTIONMAP_CUBIC = true;
  44472. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44473. break;
  44474. }
  44475. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44476. if (reflectionTexture.sphericalPolynomial) {
  44477. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44478. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44479. defines.USESPHERICALINVERTEX = false;
  44480. }
  44481. else {
  44482. defines.USESPHERICALINVERTEX = true;
  44483. }
  44484. }
  44485. }
  44486. }
  44487. else {
  44488. defines.REFLECTION = false;
  44489. defines.REFLECTIONMAP_3D = false;
  44490. defines.REFLECTIONMAP_SPHERICAL = false;
  44491. defines.REFLECTIONMAP_PLANAR = false;
  44492. defines.REFLECTIONMAP_CUBIC = false;
  44493. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44494. defines.REFLECTIONMAP_PROJECTION = false;
  44495. defines.REFLECTIONMAP_SKYBOX = false;
  44496. defines.REFLECTIONMAP_EXPLICIT = false;
  44497. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44498. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44499. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44500. defines.INVERTCUBICMAP = false;
  44501. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44502. defines.USESPHERICALINVERTEX = false;
  44503. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44504. defines.LODINREFLECTIONALPHA = false;
  44505. defines.GAMMAREFLECTION = false;
  44506. defines.RGBDREFLECTION = false;
  44507. }
  44508. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44509. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44510. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44511. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44512. }
  44513. else {
  44514. defines.LIGHTMAP = false;
  44515. }
  44516. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44517. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44518. }
  44519. else {
  44520. defines.EMISSIVE = false;
  44521. }
  44522. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44523. if (this._metallicTexture) {
  44524. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44525. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44526. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44527. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44528. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44529. }
  44530. else if (this._reflectivityTexture) {
  44531. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44532. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44533. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44534. }
  44535. else {
  44536. defines.REFLECTIVITY = false;
  44537. }
  44538. if (this._microSurfaceTexture) {
  44539. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44540. }
  44541. else {
  44542. defines.MICROSURFACEMAP = false;
  44543. }
  44544. }
  44545. else {
  44546. defines.REFLECTIVITY = false;
  44547. defines.MICROSURFACEMAP = false;
  44548. }
  44549. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44550. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44551. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44552. defines.PARALLAX = true;
  44553. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44554. }
  44555. else {
  44556. defines.PARALLAX = false;
  44557. }
  44558. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44559. }
  44560. else {
  44561. defines.BUMP = false;
  44562. }
  44563. var refractionTexture = this._getRefractionTexture();
  44564. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44565. defines.REFRACTION = true;
  44566. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44567. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44568. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44569. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44570. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44571. if (this._linkRefractionWithTransparency) {
  44572. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44573. }
  44574. }
  44575. else {
  44576. defines.REFRACTION = false;
  44577. }
  44578. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44579. defines.ENVIRONMENTBRDF = true;
  44580. }
  44581. else {
  44582. defines.ENVIRONMENTBRDF = false;
  44583. }
  44584. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44585. defines.ALPHAFROMALBEDO = true;
  44586. }
  44587. else {
  44588. defines.ALPHAFROMALBEDO = false;
  44589. }
  44590. }
  44591. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44592. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44593. defines.USEPHYSICALLIGHTFALLOFF = false;
  44594. defines.USEGLTFLIGHTFALLOFF = false;
  44595. }
  44596. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44597. defines.USEPHYSICALLIGHTFALLOFF = false;
  44598. defines.USEGLTFLIGHTFALLOFF = true;
  44599. }
  44600. else {
  44601. defines.USEPHYSICALLIGHTFALLOFF = true;
  44602. defines.USEGLTFLIGHTFALLOFF = false;
  44603. }
  44604. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44605. if (!this.backFaceCulling && this._twoSidedLighting) {
  44606. defines.TWOSIDEDLIGHTING = true;
  44607. }
  44608. else {
  44609. defines.TWOSIDEDLIGHTING = false;
  44610. }
  44611. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44612. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44613. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44614. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44615. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44616. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44617. }
  44618. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44619. this._imageProcessingConfiguration.prepareDefines(defines);
  44620. }
  44621. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44622. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44623. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44624. // Misc.
  44625. if (defines._areMiscDirty) {
  44626. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44627. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44628. }
  44629. // Values that need to be evaluated on every frame
  44630. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44631. // Attribs
  44632. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44633. };
  44634. /**
  44635. * Force shader compilation
  44636. */
  44637. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44638. var _this = this;
  44639. var localOptions = __assign({ clipPlane: false }, options);
  44640. var defines = new PBRMaterialDefines();
  44641. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44642. if (effect.isReady()) {
  44643. if (onCompiled) {
  44644. onCompiled(this);
  44645. }
  44646. }
  44647. else {
  44648. effect.onCompileObservable.add(function () {
  44649. if (onCompiled) {
  44650. onCompiled(_this);
  44651. }
  44652. });
  44653. }
  44654. };
  44655. /**
  44656. * Initializes the uniform buffer layout for the shader.
  44657. */
  44658. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44659. // Order is important !
  44660. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44661. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44662. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44663. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44664. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44665. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44666. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44667. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44668. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44669. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44670. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44671. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44672. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44673. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44674. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44675. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44676. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44677. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44678. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44679. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44680. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44681. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44682. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44683. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44684. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44685. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44686. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44687. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44688. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44689. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44690. this._uniformBuffer.addUniform("pointSize", 1);
  44691. this._uniformBuffer.create();
  44692. };
  44693. /**
  44694. * Unbinds the textures.
  44695. */
  44696. PBRBaseMaterial.prototype.unbind = function () {
  44697. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44698. this._uniformBuffer.setTexture("reflectionSampler", null);
  44699. }
  44700. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44701. this._uniformBuffer.setTexture("refractionSampler", null);
  44702. }
  44703. _super.prototype.unbind.call(this);
  44704. };
  44705. /**
  44706. * Binds the submesh data.
  44707. * @param world - The world matrix.
  44708. * @param mesh - The BJS mesh.
  44709. * @param subMesh - A submesh of the BJS mesh.
  44710. */
  44711. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44712. var scene = this.getScene();
  44713. var defines = subMesh._materialDefines;
  44714. if (!defines) {
  44715. return;
  44716. }
  44717. var effect = subMesh.effect;
  44718. if (!effect) {
  44719. return;
  44720. }
  44721. this._activeEffect = effect;
  44722. // Matrices
  44723. this.bindOnlyWorldMatrix(world);
  44724. // Normal Matrix
  44725. if (defines.OBJECTSPACE_NORMALMAP) {
  44726. world.toNormalMatrix(this._normalMatrix);
  44727. this.bindOnlyNormalMatrix(this._normalMatrix);
  44728. }
  44729. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44730. // Bones
  44731. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44732. var reflectionTexture = null;
  44733. if (mustRebind) {
  44734. this._uniformBuffer.bindToEffect(effect, "Material");
  44735. this.bindViewProjection(effect);
  44736. reflectionTexture = this._getReflectionTexture();
  44737. var refractionTexture = this._getRefractionTexture();
  44738. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44739. // Texture uniforms
  44740. if (scene.texturesEnabled) {
  44741. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44742. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44743. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44744. }
  44745. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44746. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44747. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44748. }
  44749. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44750. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44751. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44752. }
  44753. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44754. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44755. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44756. if (reflectionTexture.boundingBoxSize) {
  44757. var cubeTexture = reflectionTexture;
  44758. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44759. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44760. }
  44761. var polynomials = reflectionTexture.sphericalPolynomial;
  44762. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44763. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44764. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44765. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44766. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44767. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44768. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44769. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44770. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44771. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44772. }
  44773. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44774. }
  44775. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44776. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44777. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44778. }
  44779. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44780. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44781. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44782. }
  44783. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44784. if (this._metallicTexture) {
  44785. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44786. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44787. }
  44788. else if (this._reflectivityTexture) {
  44789. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44790. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44791. }
  44792. if (this._microSurfaceTexture) {
  44793. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44794. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44795. }
  44796. }
  44797. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44798. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44799. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44800. if (scene._mirroredCameraPosition) {
  44801. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44802. }
  44803. else {
  44804. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44805. }
  44806. }
  44807. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44808. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44809. var depth = 1.0;
  44810. if (!refractionTexture.isCube) {
  44811. if (refractionTexture.depth) {
  44812. depth = refractionTexture.depth;
  44813. }
  44814. }
  44815. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44816. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44817. }
  44818. }
  44819. // Point size
  44820. if (this.pointsCloud) {
  44821. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44822. }
  44823. // Colors
  44824. if (defines.METALLICWORKFLOW) {
  44825. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44826. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44827. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44828. }
  44829. else {
  44830. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44831. }
  44832. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44833. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44834. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44835. // Misc
  44836. this._lightingInfos.x = this._directIntensity;
  44837. this._lightingInfos.y = this._emissiveIntensity;
  44838. this._lightingInfos.z = this._environmentIntensity;
  44839. this._lightingInfos.w = this._specularIntensity;
  44840. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44841. }
  44842. // Textures
  44843. if (scene.texturesEnabled) {
  44844. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44845. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44846. }
  44847. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44848. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44849. }
  44850. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44851. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44852. }
  44853. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44854. if (defines.LODBASEDMICROSFURACE) {
  44855. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44856. }
  44857. else {
  44858. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44859. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44860. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44861. }
  44862. }
  44863. if (defines.ENVIRONMENTBRDF) {
  44864. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44865. }
  44866. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44867. if (defines.LODBASEDMICROSFURACE) {
  44868. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44869. }
  44870. else {
  44871. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44872. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44873. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44874. }
  44875. }
  44876. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44877. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44878. }
  44879. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44880. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44881. }
  44882. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44883. if (this._metallicTexture) {
  44884. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44885. }
  44886. else if (this._reflectivityTexture) {
  44887. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44888. }
  44889. if (this._microSurfaceTexture) {
  44890. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44891. }
  44892. }
  44893. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44894. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44895. }
  44896. }
  44897. // Clip plane
  44898. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44899. // Colors
  44900. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44901. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44902. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44903. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44904. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44905. }
  44906. if (mustRebind || !this.isFrozen) {
  44907. // Lights
  44908. if (scene.lightsEnabled && !this._disableLighting) {
  44909. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44910. }
  44911. // View
  44912. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44913. this.bindView(effect);
  44914. }
  44915. // Fog
  44916. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44917. // Morph targets
  44918. if (defines.NUM_MORPH_INFLUENCERS) {
  44919. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44920. }
  44921. // image processing
  44922. this._imageProcessingConfiguration.bind(this._activeEffect);
  44923. // Log. depth
  44924. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44925. }
  44926. this._uniformBuffer.update();
  44927. this._afterBind(mesh, this._activeEffect);
  44928. };
  44929. /**
  44930. * Returns the animatable textures.
  44931. * @returns - Array of animatable textures.
  44932. */
  44933. PBRBaseMaterial.prototype.getAnimatables = function () {
  44934. var results = [];
  44935. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44936. results.push(this._albedoTexture);
  44937. }
  44938. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44939. results.push(this._ambientTexture);
  44940. }
  44941. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44942. results.push(this._opacityTexture);
  44943. }
  44944. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44945. results.push(this._reflectionTexture);
  44946. }
  44947. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44948. results.push(this._emissiveTexture);
  44949. }
  44950. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44951. results.push(this._metallicTexture);
  44952. }
  44953. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44954. results.push(this._reflectivityTexture);
  44955. }
  44956. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44957. results.push(this._bumpTexture);
  44958. }
  44959. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44960. results.push(this._lightmapTexture);
  44961. }
  44962. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44963. results.push(this._refractionTexture);
  44964. }
  44965. return results;
  44966. };
  44967. /**
  44968. * Returns the texture used for reflections.
  44969. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44970. */
  44971. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44972. if (this._reflectionTexture) {
  44973. return this._reflectionTexture;
  44974. }
  44975. return this.getScene().environmentTexture;
  44976. };
  44977. /**
  44978. * Returns the texture used for refraction or null if none is used.
  44979. * @returns - Refection texture if present. If no refraction texture and refraction
  44980. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44981. */
  44982. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44983. if (this._refractionTexture) {
  44984. return this._refractionTexture;
  44985. }
  44986. if (this._linkRefractionWithTransparency) {
  44987. return this.getScene().environmentTexture;
  44988. }
  44989. return null;
  44990. };
  44991. /**
  44992. * Disposes the resources of the material.
  44993. * @param forceDisposeEffect - Forces the disposal of effects.
  44994. * @param forceDisposeTextures - Forces the disposal of all textures.
  44995. */
  44996. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44997. if (forceDisposeTextures) {
  44998. if (this._albedoTexture) {
  44999. this._albedoTexture.dispose();
  45000. }
  45001. if (this._ambientTexture) {
  45002. this._ambientTexture.dispose();
  45003. }
  45004. if (this._opacityTexture) {
  45005. this._opacityTexture.dispose();
  45006. }
  45007. if (this._reflectionTexture) {
  45008. this._reflectionTexture.dispose();
  45009. }
  45010. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45011. this._environmentBRDFTexture.dispose();
  45012. }
  45013. if (this._emissiveTexture) {
  45014. this._emissiveTexture.dispose();
  45015. }
  45016. if (this._metallicTexture) {
  45017. this._metallicTexture.dispose();
  45018. }
  45019. if (this._reflectivityTexture) {
  45020. this._reflectivityTexture.dispose();
  45021. }
  45022. if (this._bumpTexture) {
  45023. this._bumpTexture.dispose();
  45024. }
  45025. if (this._lightmapTexture) {
  45026. this._lightmapTexture.dispose();
  45027. }
  45028. if (this._refractionTexture) {
  45029. this._refractionTexture.dispose();
  45030. }
  45031. }
  45032. this._renderTargets.dispose();
  45033. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45034. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45035. }
  45036. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45037. };
  45038. /**
  45039. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45040. */
  45041. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45042. /**
  45043. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45044. * to enhance interoperability with other engines.
  45045. */
  45046. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45047. /**
  45048. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45049. * to enhance interoperability with other materials.
  45050. */
  45051. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45052. /**
  45053. * Stores the reflectivity values based on metallic roughness workflow.
  45054. */
  45055. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45056. __decorate([
  45057. BABYLON.serializeAsImageProcessingConfiguration()
  45058. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45059. __decorate([
  45060. BABYLON.serialize()
  45061. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45062. __decorate([
  45063. BABYLON.serialize()
  45064. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45065. return PBRBaseMaterial;
  45066. }(BABYLON.PushMaterial));
  45067. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45068. })(BABYLON || (BABYLON = {}));
  45069. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45070. var BABYLON;
  45071. (function (BABYLON) {
  45072. /**
  45073. * The Physically based simple base material of BJS.
  45074. *
  45075. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45076. * It is used as the base class for both the specGloss and metalRough conventions.
  45077. */
  45078. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45079. __extends(PBRBaseSimpleMaterial, _super);
  45080. /**
  45081. * Instantiates a new PBRMaterial instance.
  45082. *
  45083. * @param name The material name
  45084. * @param scene The scene the material will be use in.
  45085. */
  45086. function PBRBaseSimpleMaterial(name, scene) {
  45087. var _this = _super.call(this, name, scene) || this;
  45088. /**
  45089. * Number of Simultaneous lights allowed on the material.
  45090. */
  45091. _this.maxSimultaneousLights = 4;
  45092. /**
  45093. * If sets to true, disables all the lights affecting the material.
  45094. */
  45095. _this.disableLighting = false;
  45096. /**
  45097. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45098. */
  45099. _this.invertNormalMapX = false;
  45100. /**
  45101. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45102. */
  45103. _this.invertNormalMapY = false;
  45104. /**
  45105. * Emissivie color used to self-illuminate the model.
  45106. */
  45107. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45108. /**
  45109. * Occlusion Channel Strenght.
  45110. */
  45111. _this.occlusionStrength = 1.0;
  45112. _this.useLightmapAsShadowmap = false;
  45113. _this._useAlphaFromAlbedoTexture = true;
  45114. _this._useAmbientInGrayScale = true;
  45115. return _this;
  45116. }
  45117. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45118. /**
  45119. * Gets the current double sided mode.
  45120. */
  45121. get: function () {
  45122. return this._twoSidedLighting;
  45123. },
  45124. /**
  45125. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45126. */
  45127. set: function (value) {
  45128. if (this._twoSidedLighting === value) {
  45129. return;
  45130. }
  45131. this._twoSidedLighting = value;
  45132. this.backFaceCulling = !value;
  45133. this._markAllSubMeshesAsTexturesDirty();
  45134. },
  45135. enumerable: true,
  45136. configurable: true
  45137. });
  45138. /**
  45139. * Return the active textures of the material.
  45140. */
  45141. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45142. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45143. if (this.environmentTexture) {
  45144. activeTextures.push(this.environmentTexture);
  45145. }
  45146. if (this.normalTexture) {
  45147. activeTextures.push(this.normalTexture);
  45148. }
  45149. if (this.emissiveTexture) {
  45150. activeTextures.push(this.emissiveTexture);
  45151. }
  45152. if (this.occlusionTexture) {
  45153. activeTextures.push(this.occlusionTexture);
  45154. }
  45155. if (this.lightmapTexture) {
  45156. activeTextures.push(this.lightmapTexture);
  45157. }
  45158. return activeTextures;
  45159. };
  45160. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45161. if (_super.prototype.hasTexture.call(this, texture)) {
  45162. return true;
  45163. }
  45164. if (this.lightmapTexture === texture) {
  45165. return true;
  45166. }
  45167. return false;
  45168. };
  45169. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45170. return "PBRBaseSimpleMaterial";
  45171. };
  45172. __decorate([
  45173. BABYLON.serialize(),
  45174. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45175. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45176. __decorate([
  45177. BABYLON.serialize(),
  45178. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45179. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45180. __decorate([
  45181. BABYLON.serializeAsTexture(),
  45182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45183. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45184. __decorate([
  45185. BABYLON.serialize(),
  45186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45187. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45188. __decorate([
  45189. BABYLON.serialize(),
  45190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45191. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45192. __decorate([
  45193. BABYLON.serializeAsTexture(),
  45194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45195. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45196. __decorate([
  45197. BABYLON.serializeAsColor3("emissive"),
  45198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45199. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45200. __decorate([
  45201. BABYLON.serializeAsTexture(),
  45202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45203. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45204. __decorate([
  45205. BABYLON.serialize(),
  45206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45207. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45208. __decorate([
  45209. BABYLON.serializeAsTexture(),
  45210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45211. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45212. __decorate([
  45213. BABYLON.serialize(),
  45214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45215. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45216. __decorate([
  45217. BABYLON.serialize()
  45218. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45219. __decorate([
  45220. BABYLON.serializeAsTexture(),
  45221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45222. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45223. __decorate([
  45224. BABYLON.serialize(),
  45225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45226. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45227. return PBRBaseSimpleMaterial;
  45228. }(BABYLON.PBRBaseMaterial));
  45229. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45230. })(BABYLON || (BABYLON = {}));
  45231. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45232. 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 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 vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform 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 vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 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};"};
  45233. var BABYLON;
  45234. (function (BABYLON) {
  45235. /**
  45236. * The Physically based material 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 PBRMaterial = /** @class */ (function (_super) {
  45243. __extends(PBRMaterial, _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 PBRMaterial(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. * Debug Control allowing disabling the bump map on this material.
  45274. */
  45275. _this.disableBumpMap = false;
  45276. /**
  45277. * AKA Occlusion Texture Intensity in other nomenclature.
  45278. */
  45279. _this.ambientTextureStrength = 1.0;
  45280. /**
  45281. * The color of a material in ambient lighting.
  45282. */
  45283. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45284. /**
  45285. * AKA Diffuse Color in other nomenclature.
  45286. */
  45287. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45288. /**
  45289. * AKA Specular Color in other nomenclature.
  45290. */
  45291. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45292. /**
  45293. * The color reflected from the material.
  45294. */
  45295. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45296. /**
  45297. * The color emitted from the material.
  45298. */
  45299. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45300. /**
  45301. * AKA Glossiness in other nomenclature.
  45302. */
  45303. _this.microSurface = 1.0;
  45304. /**
  45305. * source material index of refraction (IOR)' / 'destination material IOR.
  45306. */
  45307. _this.indexOfRefraction = 0.66;
  45308. /**
  45309. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45310. */
  45311. _this.invertRefractionY = false;
  45312. /**
  45313. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45314. * Materials half opaque for instance using refraction could benefit from this control.
  45315. */
  45316. _this.linkRefractionWithTransparency = false;
  45317. _this.useLightmapAsShadowmap = false;
  45318. /**
  45319. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45320. */
  45321. _this.useAlphaFromAlbedoTexture = false;
  45322. /**
  45323. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45324. */
  45325. _this.forceAlphaTest = false;
  45326. /**
  45327. * Defines the alpha limits in alpha test mode.
  45328. */
  45329. _this.alphaCutOff = 0.4;
  45330. /**
  45331. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45332. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45333. */
  45334. _this.useSpecularOverAlpha = true;
  45335. /**
  45336. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45337. */
  45338. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45339. /**
  45340. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45341. */
  45342. _this.useRoughnessFromMetallicTextureAlpha = true;
  45343. /**
  45344. * Specifies if the metallic texture contains the roughness information in its green channel.
  45345. */
  45346. _this.useRoughnessFromMetallicTextureGreen = false;
  45347. /**
  45348. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45349. */
  45350. _this.useMetallnessFromMetallicTextureBlue = false;
  45351. /**
  45352. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45353. */
  45354. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45355. /**
  45356. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45357. */
  45358. _this.useAmbientInGrayScale = false;
  45359. /**
  45360. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45361. * The material will try to infer what glossiness each pixel should be.
  45362. */
  45363. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45364. /**
  45365. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45366. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45367. */
  45368. _this.useRadianceOverAlpha = true;
  45369. /**
  45370. * Allows using an object space normal map (instead of tangent space).
  45371. */
  45372. _this.useObjectSpaceNormalMap = false;
  45373. /**
  45374. * Allows using the bump map in parallax mode.
  45375. */
  45376. _this.useParallax = false;
  45377. /**
  45378. * Allows using the bump map in parallax occlusion mode.
  45379. */
  45380. _this.useParallaxOcclusion = false;
  45381. /**
  45382. * Controls the scale bias of the parallax mode.
  45383. */
  45384. _this.parallaxScaleBias = 0.05;
  45385. /**
  45386. * If sets to true, disables all the lights affecting the material.
  45387. */
  45388. _this.disableLighting = false;
  45389. /**
  45390. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45391. */
  45392. _this.forceIrradianceInFragment = false;
  45393. /**
  45394. * Number of Simultaneous lights allowed on the material.
  45395. */
  45396. _this.maxSimultaneousLights = 4;
  45397. /**
  45398. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45399. */
  45400. _this.invertNormalMapX = false;
  45401. /**
  45402. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45403. */
  45404. _this.invertNormalMapY = false;
  45405. /**
  45406. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45407. */
  45408. _this.twoSidedLighting = false;
  45409. /**
  45410. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45411. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45412. */
  45413. _this.useAlphaFresnel = false;
  45414. /**
  45415. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45416. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45417. */
  45418. _this.useLinearAlphaFresnel = false;
  45419. /**
  45420. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45421. * And/Or occlude the blended part.
  45422. */
  45423. _this.environmentBRDFTexture = null;
  45424. /**
  45425. * Force normal to face away from face.
  45426. */
  45427. _this.forceNormalForward = false;
  45428. /**
  45429. * Enables specular anti aliasing in the PBR shader.
  45430. * It will both interacts on the Geometry for analytical and IBL lighting.
  45431. * It also prefilter the roughness map based on the bump values.
  45432. */
  45433. _this.enableSpecularAntiAliasing = false;
  45434. /**
  45435. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45436. * makes the reflect vector face the model (under horizon).
  45437. */
  45438. _this.useHorizonOcclusion = true;
  45439. /**
  45440. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45441. * too much the area relying on ambient texture to define their ambient occlusion.
  45442. */
  45443. _this.useRadianceOcclusion = true;
  45444. /**
  45445. * If set to true, no lighting calculations will be applied.
  45446. */
  45447. _this.unlit = false;
  45448. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45449. return _this;
  45450. }
  45451. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45452. /**
  45453. * BJS is using an harcoded light falloff based on a manually sets up range.
  45454. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45455. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45456. */
  45457. get: function () {
  45458. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45459. },
  45460. /**
  45461. * BJS is using an harcoded light falloff based on a manually sets up range.
  45462. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45463. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45464. */
  45465. set: function (value) {
  45466. if (value !== this.usePhysicalLightFalloff) {
  45467. // Ensure the effect will be rebuilt.
  45468. this._markAllSubMeshesAsTexturesDirty();
  45469. if (value) {
  45470. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45471. }
  45472. else {
  45473. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45474. }
  45475. }
  45476. },
  45477. enumerable: true,
  45478. configurable: true
  45479. });
  45480. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45481. /**
  45482. * In order to support the falloff compatibility with gltf, a special mode has been added
  45483. * to reproduce the gltf light falloff.
  45484. */
  45485. get: function () {
  45486. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45487. },
  45488. /**
  45489. * In order to support the falloff compatibility with gltf, a special mode has been added
  45490. * to reproduce the gltf light falloff.
  45491. */
  45492. set: function (value) {
  45493. if (value !== this.useGLTFLightFalloff) {
  45494. // Ensure the effect will be rebuilt.
  45495. this._markAllSubMeshesAsTexturesDirty();
  45496. if (value) {
  45497. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45498. }
  45499. else {
  45500. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45501. }
  45502. }
  45503. },
  45504. enumerable: true,
  45505. configurable: true
  45506. });
  45507. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45508. /**
  45509. * Gets the image processing configuration used either in this material.
  45510. */
  45511. get: function () {
  45512. return this._imageProcessingConfiguration;
  45513. },
  45514. /**
  45515. * Sets the Default image processing configuration used either in the this material.
  45516. *
  45517. * If sets to null, the scene one is in use.
  45518. */
  45519. set: function (value) {
  45520. this._attachImageProcessingConfiguration(value);
  45521. // Ensure the effect will be rebuilt.
  45522. this._markAllSubMeshesAsTexturesDirty();
  45523. },
  45524. enumerable: true,
  45525. configurable: true
  45526. });
  45527. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45528. /**
  45529. * Gets wether the color curves effect is enabled.
  45530. */
  45531. get: function () {
  45532. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45533. },
  45534. /**
  45535. * Sets wether the color curves effect is enabled.
  45536. */
  45537. set: function (value) {
  45538. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45539. },
  45540. enumerable: true,
  45541. configurable: true
  45542. });
  45543. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45544. /**
  45545. * Gets wether the color grading effect is enabled.
  45546. */
  45547. get: function () {
  45548. return this.imageProcessingConfiguration.colorGradingEnabled;
  45549. },
  45550. /**
  45551. * Gets wether the color grading effect is enabled.
  45552. */
  45553. set: function (value) {
  45554. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45555. },
  45556. enumerable: true,
  45557. configurable: true
  45558. });
  45559. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45560. /**
  45561. * Gets wether tonemapping is enabled or not.
  45562. */
  45563. get: function () {
  45564. return this._imageProcessingConfiguration.toneMappingEnabled;
  45565. },
  45566. /**
  45567. * Sets wether tonemapping is enabled or not
  45568. */
  45569. set: function (value) {
  45570. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45571. },
  45572. enumerable: true,
  45573. configurable: true
  45574. });
  45575. ;
  45576. ;
  45577. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45578. /**
  45579. * The camera exposure used on this material.
  45580. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45581. * This corresponds to a photographic exposure.
  45582. */
  45583. get: function () {
  45584. return this._imageProcessingConfiguration.exposure;
  45585. },
  45586. /**
  45587. * The camera exposure used on this material.
  45588. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45589. * This corresponds to a photographic exposure.
  45590. */
  45591. set: function (value) {
  45592. this._imageProcessingConfiguration.exposure = value;
  45593. },
  45594. enumerable: true,
  45595. configurable: true
  45596. });
  45597. ;
  45598. ;
  45599. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45600. /**
  45601. * Gets The camera contrast used on this material.
  45602. */
  45603. get: function () {
  45604. return this._imageProcessingConfiguration.contrast;
  45605. },
  45606. /**
  45607. * Sets The camera contrast used on this material.
  45608. */
  45609. set: function (value) {
  45610. this._imageProcessingConfiguration.contrast = value;
  45611. },
  45612. enumerable: true,
  45613. configurable: true
  45614. });
  45615. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45616. /**
  45617. * Gets the Color Grading 2D Lookup Texture.
  45618. */
  45619. get: function () {
  45620. return this._imageProcessingConfiguration.colorGradingTexture;
  45621. },
  45622. /**
  45623. * Sets the Color Grading 2D Lookup Texture.
  45624. */
  45625. set: function (value) {
  45626. this._imageProcessingConfiguration.colorGradingTexture = value;
  45627. },
  45628. enumerable: true,
  45629. configurable: true
  45630. });
  45631. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45632. /**
  45633. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45634. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45635. * 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;
  45636. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45637. */
  45638. get: function () {
  45639. return this._imageProcessingConfiguration.colorCurves;
  45640. },
  45641. /**
  45642. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45643. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45644. * 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;
  45645. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45646. */
  45647. set: function (value) {
  45648. this._imageProcessingConfiguration.colorCurves = value;
  45649. },
  45650. enumerable: true,
  45651. configurable: true
  45652. });
  45653. /**
  45654. * Returns the name of this material class.
  45655. */
  45656. PBRMaterial.prototype.getClassName = function () {
  45657. return "PBRMaterial";
  45658. };
  45659. /**
  45660. * Returns an array of the actively used textures.
  45661. * @returns - Array of BaseTextures
  45662. */
  45663. PBRMaterial.prototype.getActiveTextures = function () {
  45664. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45665. if (this._albedoTexture) {
  45666. activeTextures.push(this._albedoTexture);
  45667. }
  45668. if (this._ambientTexture) {
  45669. activeTextures.push(this._ambientTexture);
  45670. }
  45671. if (this._opacityTexture) {
  45672. activeTextures.push(this._opacityTexture);
  45673. }
  45674. if (this._reflectionTexture) {
  45675. activeTextures.push(this._reflectionTexture);
  45676. }
  45677. if (this._emissiveTexture) {
  45678. activeTextures.push(this._emissiveTexture);
  45679. }
  45680. if (this._reflectivityTexture) {
  45681. activeTextures.push(this._reflectivityTexture);
  45682. }
  45683. if (this._metallicTexture) {
  45684. activeTextures.push(this._metallicTexture);
  45685. }
  45686. if (this._microSurfaceTexture) {
  45687. activeTextures.push(this._microSurfaceTexture);
  45688. }
  45689. if (this._bumpTexture) {
  45690. activeTextures.push(this._bumpTexture);
  45691. }
  45692. if (this._lightmapTexture) {
  45693. activeTextures.push(this._lightmapTexture);
  45694. }
  45695. if (this._refractionTexture) {
  45696. activeTextures.push(this._refractionTexture);
  45697. }
  45698. return activeTextures;
  45699. };
  45700. /**
  45701. * Checks to see if a texture is used in the material.
  45702. * @param texture - Base texture to use.
  45703. * @returns - Boolean specifying if a texture is used in the material.
  45704. */
  45705. PBRMaterial.prototype.hasTexture = function (texture) {
  45706. if (_super.prototype.hasTexture.call(this, texture)) {
  45707. return true;
  45708. }
  45709. if (this._albedoTexture === texture) {
  45710. return true;
  45711. }
  45712. if (this._ambientTexture === texture) {
  45713. return true;
  45714. }
  45715. if (this._opacityTexture === texture) {
  45716. return true;
  45717. }
  45718. if (this._reflectionTexture === texture) {
  45719. return true;
  45720. }
  45721. if (this._reflectivityTexture === texture) {
  45722. return true;
  45723. }
  45724. if (this._metallicTexture === texture) {
  45725. return true;
  45726. }
  45727. if (this._microSurfaceTexture === texture) {
  45728. return true;
  45729. }
  45730. if (this._bumpTexture === texture) {
  45731. return true;
  45732. }
  45733. if (this._lightmapTexture === texture) {
  45734. return true;
  45735. }
  45736. if (this._refractionTexture === texture) {
  45737. return true;
  45738. }
  45739. return false;
  45740. };
  45741. /**
  45742. * Makes a duplicate of the current material.
  45743. * @param name - name to use for the new material.
  45744. */
  45745. PBRMaterial.prototype.clone = function (name) {
  45746. var _this = this;
  45747. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45748. clone.id = name;
  45749. clone.name = name;
  45750. return clone;
  45751. };
  45752. /**
  45753. * Serializes this PBR Material.
  45754. * @returns - An object with the serialized material.
  45755. */
  45756. PBRMaterial.prototype.serialize = function () {
  45757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45758. serializationObject.customType = "BABYLON.PBRMaterial";
  45759. return serializationObject;
  45760. };
  45761. // Statics
  45762. /**
  45763. * Parses a PBR Material from a serialized object.
  45764. * @param source - Serialized object.
  45765. * @param scene - BJS scene instance.
  45766. * @param rootUrl - url for the scene object
  45767. * @returns - PBRMaterial
  45768. */
  45769. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45770. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45771. };
  45772. /**
  45773. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45774. */
  45775. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45776. /**
  45777. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45778. */
  45779. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45780. /**
  45781. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45782. */
  45783. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45784. /**
  45785. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45786. * They are also discarded below the alpha cutoff threshold to improve performances.
  45787. */
  45788. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMaterial.prototype, "directIntensity", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45797. __decorate([
  45798. BABYLON.serialize(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45800. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45801. __decorate([
  45802. BABYLON.serialize(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45804. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45805. __decorate([
  45806. BABYLON.serialize(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45808. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45809. __decorate([
  45810. BABYLON.serializeAsTexture(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45812. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45813. __decorate([
  45814. BABYLON.serializeAsTexture(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45816. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45817. __decorate([
  45818. BABYLON.serialize(),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45821. __decorate([
  45822. BABYLON.serializeAsTexture(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45824. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45825. __decorate([
  45826. BABYLON.serializeAsTexture(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45828. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsTexture(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45832. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45833. __decorate([
  45834. BABYLON.serializeAsTexture(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45836. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45837. __decorate([
  45838. BABYLON.serializeAsTexture(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45840. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45844. ], PBRMaterial.prototype, "metallic", void 0);
  45845. __decorate([
  45846. BABYLON.serialize(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45848. ], PBRMaterial.prototype, "roughness", void 0);
  45849. __decorate([
  45850. BABYLON.serializeAsTexture(),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45852. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45853. __decorate([
  45854. BABYLON.serializeAsTexture(),
  45855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45856. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45857. __decorate([
  45858. BABYLON.serializeAsTexture(),
  45859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45860. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45861. __decorate([
  45862. BABYLON.serializeAsTexture(),
  45863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45864. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45865. __decorate([
  45866. BABYLON.serializeAsColor3("ambient"),
  45867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45868. ], PBRMaterial.prototype, "ambientColor", void 0);
  45869. __decorate([
  45870. BABYLON.serializeAsColor3("albedo"),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45872. ], PBRMaterial.prototype, "albedoColor", void 0);
  45873. __decorate([
  45874. BABYLON.serializeAsColor3("reflectivity"),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45876. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45877. __decorate([
  45878. BABYLON.serializeAsColor3("reflection"),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45880. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45881. __decorate([
  45882. BABYLON.serializeAsColor3("emissive"),
  45883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45884. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45885. __decorate([
  45886. BABYLON.serialize(),
  45887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45888. ], PBRMaterial.prototype, "microSurface", void 0);
  45889. __decorate([
  45890. BABYLON.serialize(),
  45891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45892. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45893. __decorate([
  45894. BABYLON.serialize(),
  45895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45896. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45897. __decorate([
  45898. BABYLON.serialize(),
  45899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45900. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45901. __decorate([
  45902. BABYLON.serialize(),
  45903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45904. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45905. __decorate([
  45906. BABYLON.serialize(),
  45907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45908. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45909. __decorate([
  45910. BABYLON.serialize(),
  45911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45912. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45913. __decorate([
  45914. BABYLON.serialize(),
  45915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45916. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45917. __decorate([
  45918. BABYLON.serialize(),
  45919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45920. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45921. __decorate([
  45922. BABYLON.serialize(),
  45923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45924. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45925. __decorate([
  45926. BABYLON.serialize(),
  45927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45928. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45929. __decorate([
  45930. BABYLON.serialize(),
  45931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45932. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45933. __decorate([
  45934. BABYLON.serialize(),
  45935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45936. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45937. __decorate([
  45938. BABYLON.serialize(),
  45939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45940. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45941. __decorate([
  45942. BABYLON.serialize(),
  45943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45944. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45945. __decorate([
  45946. BABYLON.serialize(),
  45947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45948. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45949. __decorate([
  45950. BABYLON.serialize()
  45951. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45952. __decorate([
  45953. BABYLON.serialize()
  45954. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45955. __decorate([
  45956. BABYLON.serialize(),
  45957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45958. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45959. __decorate([
  45960. BABYLON.serialize(),
  45961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45962. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45963. __decorate([
  45964. BABYLON.serialize(),
  45965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45966. ], PBRMaterial.prototype, "useParallax", void 0);
  45967. __decorate([
  45968. BABYLON.serialize(),
  45969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45970. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45971. __decorate([
  45972. BABYLON.serialize(),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45974. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45975. __decorate([
  45976. BABYLON.serialize(),
  45977. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45978. ], PBRMaterial.prototype, "disableLighting", void 0);
  45979. __decorate([
  45980. BABYLON.serialize(),
  45981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45982. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45983. __decorate([
  45984. BABYLON.serialize(),
  45985. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45986. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45987. __decorate([
  45988. BABYLON.serialize(),
  45989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45990. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45991. __decorate([
  45992. BABYLON.serialize(),
  45993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45994. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45995. __decorate([
  45996. BABYLON.serialize(),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45998. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46002. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46003. __decorate([
  46004. BABYLON.serialize(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46006. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46007. __decorate([
  46008. BABYLON.serializeAsTexture(),
  46009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46010. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46011. __decorate([
  46012. BABYLON.serialize(),
  46013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46014. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46015. __decorate([
  46016. BABYLON.serialize(),
  46017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46018. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46019. __decorate([
  46020. BABYLON.serialize(),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46022. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46023. __decorate([
  46024. BABYLON.serialize(),
  46025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46026. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46027. __decorate([
  46028. BABYLON.serialize(),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46030. ], PBRMaterial.prototype, "unlit", void 0);
  46031. return PBRMaterial;
  46032. }(BABYLON.PBRBaseMaterial));
  46033. BABYLON.PBRMaterial = PBRMaterial;
  46034. })(BABYLON || (BABYLON = {}));
  46035. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46036. var BABYLON;
  46037. (function (BABYLON) {
  46038. /**
  46039. * The PBR material of BJS following the metal roughness convention.
  46040. *
  46041. * This fits to the PBR convention in the GLTF definition:
  46042. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46043. */
  46044. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46045. __extends(PBRMetallicRoughnessMaterial, _super);
  46046. /**
  46047. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46048. *
  46049. * @param name The material name
  46050. * @param scene The scene the material will be use in.
  46051. */
  46052. function PBRMetallicRoughnessMaterial(name, scene) {
  46053. var _this = _super.call(this, name, scene) || this;
  46054. _this._useRoughnessFromMetallicTextureAlpha = false;
  46055. _this._useRoughnessFromMetallicTextureGreen = true;
  46056. _this._useMetallnessFromMetallicTextureBlue = true;
  46057. _this.metallic = 1.0;
  46058. _this.roughness = 1.0;
  46059. return _this;
  46060. }
  46061. /**
  46062. * Return the currrent class name of the material.
  46063. */
  46064. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46065. return "PBRMetallicRoughnessMaterial";
  46066. };
  46067. /**
  46068. * Return the active textures of the material.
  46069. */
  46070. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46071. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46072. if (this.baseTexture) {
  46073. activeTextures.push(this.baseTexture);
  46074. }
  46075. if (this.metallicRoughnessTexture) {
  46076. activeTextures.push(this.metallicRoughnessTexture);
  46077. }
  46078. return activeTextures;
  46079. };
  46080. /**
  46081. * Checks to see if a texture is used in the material.
  46082. * @param texture - Base texture to use.
  46083. * @returns - Boolean specifying if a texture is used in the material.
  46084. */
  46085. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46086. if (_super.prototype.hasTexture.call(this, texture)) {
  46087. return true;
  46088. }
  46089. if (this.baseTexture === texture) {
  46090. return true;
  46091. }
  46092. if (this.metallicRoughnessTexture === texture) {
  46093. return true;
  46094. }
  46095. return false;
  46096. };
  46097. /**
  46098. * Makes a duplicate of the current material.
  46099. * @param name - name to use for the new material.
  46100. */
  46101. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46102. var _this = this;
  46103. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46104. clone.id = name;
  46105. clone.name = name;
  46106. return clone;
  46107. };
  46108. /**
  46109. * Serialize the material to a parsable JSON object.
  46110. */
  46111. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46112. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46113. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46114. return serializationObject;
  46115. };
  46116. /**
  46117. * Parses a JSON object correponding to the serialize function.
  46118. */
  46119. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46120. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46121. };
  46122. __decorate([
  46123. BABYLON.serializeAsColor3(),
  46124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46125. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46126. __decorate([
  46127. BABYLON.serializeAsTexture(),
  46128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46129. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46130. __decorate([
  46131. BABYLON.serialize(),
  46132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46133. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46134. __decorate([
  46135. BABYLON.serialize(),
  46136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46137. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46138. __decorate([
  46139. BABYLON.serializeAsTexture(),
  46140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46141. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46142. return PBRMetallicRoughnessMaterial;
  46143. }(BABYLON.PBRBaseSimpleMaterial));
  46144. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46145. })(BABYLON || (BABYLON = {}));
  46146. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46147. var BABYLON;
  46148. (function (BABYLON) {
  46149. /**
  46150. * The PBR material of BJS following the specular glossiness convention.
  46151. *
  46152. * This fits to the PBR convention in the GLTF definition:
  46153. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46154. */
  46155. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46156. __extends(PBRSpecularGlossinessMaterial, _super);
  46157. /**
  46158. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46159. *
  46160. * @param name The material name
  46161. * @param scene The scene the material will be use in.
  46162. */
  46163. function PBRSpecularGlossinessMaterial(name, scene) {
  46164. var _this = _super.call(this, name, scene) || this;
  46165. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46166. return _this;
  46167. }
  46168. /**
  46169. * Return the currrent class name of the material.
  46170. */
  46171. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46172. return "PBRSpecularGlossinessMaterial";
  46173. };
  46174. /**
  46175. * Return the active textures of the material.
  46176. */
  46177. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46178. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46179. if (this.diffuseTexture) {
  46180. activeTextures.push(this.diffuseTexture);
  46181. }
  46182. if (this.specularGlossinessTexture) {
  46183. activeTextures.push(this.specularGlossinessTexture);
  46184. }
  46185. return activeTextures;
  46186. };
  46187. /**
  46188. * Checks to see if a texture is used in the material.
  46189. * @param texture - Base texture to use.
  46190. * @returns - Boolean specifying if a texture is used in the material.
  46191. */
  46192. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46193. if (_super.prototype.hasTexture.call(this, texture)) {
  46194. return true;
  46195. }
  46196. if (this.diffuseTexture === texture) {
  46197. return true;
  46198. }
  46199. if (this.specularGlossinessTexture === texture) {
  46200. return true;
  46201. }
  46202. return false;
  46203. };
  46204. /**
  46205. * Makes a duplicate of the current material.
  46206. * @param name - name to use for the new material.
  46207. */
  46208. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46209. var _this = this;
  46210. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46211. clone.id = name;
  46212. clone.name = name;
  46213. return clone;
  46214. };
  46215. /**
  46216. * Serialize the material to a parsable JSON object.
  46217. */
  46218. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46219. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46220. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46221. return serializationObject;
  46222. };
  46223. /**
  46224. * Parses a JSON object correponding to the serialize function.
  46225. */
  46226. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46227. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46228. };
  46229. __decorate([
  46230. BABYLON.serializeAsColor3("diffuse"),
  46231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46232. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46233. __decorate([
  46234. BABYLON.serializeAsTexture(),
  46235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46236. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46237. __decorate([
  46238. BABYLON.serializeAsColor3("specular"),
  46239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46240. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46241. __decorate([
  46242. BABYLON.serialize(),
  46243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46244. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46245. __decorate([
  46246. BABYLON.serializeAsTexture(),
  46247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46248. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46249. return PBRSpecularGlossinessMaterial;
  46250. }(BABYLON.PBRBaseSimpleMaterial));
  46251. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46252. })(BABYLON || (BABYLON = {}));
  46253. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46254. var BABYLON;
  46255. (function (BABYLON) {
  46256. BABYLON.CameraInputTypes = {};
  46257. var CameraInputsManager = /** @class */ (function () {
  46258. function CameraInputsManager(camera) {
  46259. this.attached = {};
  46260. this.camera = camera;
  46261. this.checkInputs = function () { };
  46262. }
  46263. /**
  46264. * Add an input method to a camera
  46265. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46266. * @param input camera input method
  46267. */
  46268. CameraInputsManager.prototype.add = function (input) {
  46269. var type = input.getSimpleName();
  46270. if (this.attached[type]) {
  46271. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46272. return;
  46273. }
  46274. this.attached[type] = input;
  46275. input.camera = this.camera;
  46276. //for checkInputs, we are dynamically creating a function
  46277. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46278. if (input.checkInputs) {
  46279. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46280. }
  46281. if (this.attachedElement) {
  46282. input.attachControl(this.attachedElement);
  46283. }
  46284. };
  46285. /**
  46286. * Remove a specific input method from a camera
  46287. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46288. * @param inputToRemove camera input method
  46289. */
  46290. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46291. for (var cam in this.attached) {
  46292. var input = this.attached[cam];
  46293. if (input === inputToRemove) {
  46294. input.detachControl(this.attachedElement);
  46295. input.camera = null;
  46296. delete this.attached[cam];
  46297. this.rebuildInputCheck();
  46298. }
  46299. }
  46300. };
  46301. CameraInputsManager.prototype.removeByType = function (inputType) {
  46302. for (var cam in this.attached) {
  46303. var input = this.attached[cam];
  46304. if (input.getClassName() === inputType) {
  46305. input.detachControl(this.attachedElement);
  46306. input.camera = null;
  46307. delete this.attached[cam];
  46308. this.rebuildInputCheck();
  46309. }
  46310. }
  46311. };
  46312. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46313. var current = this.checkInputs;
  46314. return function () {
  46315. current();
  46316. fn();
  46317. };
  46318. };
  46319. CameraInputsManager.prototype.attachInput = function (input) {
  46320. if (this.attachedElement) {
  46321. input.attachControl(this.attachedElement, this.noPreventDefault);
  46322. }
  46323. };
  46324. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46325. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46326. if (this.attachedElement) {
  46327. return;
  46328. }
  46329. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46330. this.attachedElement = element;
  46331. this.noPreventDefault = noPreventDefault;
  46332. for (var cam in this.attached) {
  46333. this.attached[cam].attachControl(element, noPreventDefault);
  46334. }
  46335. };
  46336. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46337. if (disconnect === void 0) { disconnect = false; }
  46338. if (this.attachedElement !== element) {
  46339. return;
  46340. }
  46341. for (var cam in this.attached) {
  46342. this.attached[cam].detachControl(element);
  46343. if (disconnect) {
  46344. this.attached[cam].camera = null;
  46345. }
  46346. }
  46347. this.attachedElement = null;
  46348. };
  46349. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46350. this.checkInputs = function () { };
  46351. for (var cam in this.attached) {
  46352. var input = this.attached[cam];
  46353. if (input.checkInputs) {
  46354. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46355. }
  46356. }
  46357. };
  46358. /**
  46359. * Remove all attached input methods from a camera
  46360. */
  46361. CameraInputsManager.prototype.clear = function () {
  46362. if (this.attachedElement) {
  46363. this.detachElement(this.attachedElement, true);
  46364. }
  46365. this.attached = {};
  46366. this.attachedElement = null;
  46367. this.checkInputs = function () { };
  46368. };
  46369. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46370. var inputs = {};
  46371. for (var cam in this.attached) {
  46372. var input = this.attached[cam];
  46373. var res = BABYLON.SerializationHelper.Serialize(input);
  46374. inputs[input.getClassName()] = res;
  46375. }
  46376. serializedCamera.inputsmgr = inputs;
  46377. };
  46378. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46379. var parsedInputs = parsedCamera.inputsmgr;
  46380. if (parsedInputs) {
  46381. this.clear();
  46382. for (var n in parsedInputs) {
  46383. var construct = BABYLON.CameraInputTypes[n];
  46384. if (construct) {
  46385. var parsedinput = parsedInputs[n];
  46386. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46387. this.add(input);
  46388. }
  46389. }
  46390. }
  46391. else {
  46392. //2016-03-08 this part is for managing backward compatibility
  46393. for (var n in this.attached) {
  46394. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46395. if (construct) {
  46396. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46397. this.remove(this.attached[n]);
  46398. this.add(input);
  46399. }
  46400. }
  46401. }
  46402. };
  46403. return CameraInputsManager;
  46404. }());
  46405. BABYLON.CameraInputsManager = CameraInputsManager;
  46406. })(BABYLON || (BABYLON = {}));
  46407. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46408. var BABYLON;
  46409. (function (BABYLON) {
  46410. var TargetCamera = /** @class */ (function (_super) {
  46411. __extends(TargetCamera, _super);
  46412. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46413. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46414. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46415. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46416. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46417. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46418. _this.speed = 2.0;
  46419. _this.noRotationConstraint = false;
  46420. _this.lockedTarget = null;
  46421. /** @hidden */
  46422. _this._currentTarget = BABYLON.Vector3.Zero();
  46423. /** @hidden */
  46424. _this._viewMatrix = BABYLON.Matrix.Zero();
  46425. /** @hidden */
  46426. _this._camMatrix = BABYLON.Matrix.Zero();
  46427. /** @hidden */
  46428. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46429. /** @hidden */
  46430. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46431. /** @hidden */
  46432. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46433. /** @hidden */
  46434. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46435. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46436. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46437. _this._defaultUp = BABYLON.Vector3.Up();
  46438. _this._cachedRotationZ = 0;
  46439. return _this;
  46440. }
  46441. TargetCamera.prototype.getFrontPosition = function (distance) {
  46442. this.getWorldMatrix();
  46443. var direction = this.getTarget().subtract(this.position);
  46444. direction.normalize();
  46445. direction.scaleInPlace(distance);
  46446. return this.globalPosition.add(direction);
  46447. };
  46448. /** @hidden */
  46449. TargetCamera.prototype._getLockedTargetPosition = function () {
  46450. if (!this.lockedTarget) {
  46451. return null;
  46452. }
  46453. if (this.lockedTarget.absolutePosition) {
  46454. this.lockedTarget.computeWorldMatrix();
  46455. }
  46456. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46457. };
  46458. TargetCamera.prototype.storeState = function () {
  46459. this._storedPosition = this.position.clone();
  46460. this._storedRotation = this.rotation.clone();
  46461. if (this.rotationQuaternion) {
  46462. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46463. }
  46464. return _super.prototype.storeState.call(this);
  46465. };
  46466. /**
  46467. * Restored camera state. You must call storeState() first
  46468. * @returns whether it was successful or not
  46469. * @hidden
  46470. */
  46471. TargetCamera.prototype._restoreStateValues = function () {
  46472. if (!_super.prototype._restoreStateValues.call(this)) {
  46473. return false;
  46474. }
  46475. this.position = this._storedPosition.clone();
  46476. this.rotation = this._storedRotation.clone();
  46477. if (this.rotationQuaternion) {
  46478. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46479. }
  46480. this.cameraDirection.copyFromFloats(0, 0, 0);
  46481. this.cameraRotation.copyFromFloats(0, 0);
  46482. return true;
  46483. };
  46484. // Cache
  46485. /** @hidden */
  46486. TargetCamera.prototype._initCache = function () {
  46487. _super.prototype._initCache.call(this);
  46488. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46489. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46490. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46491. };
  46492. /** @hidden */
  46493. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46494. if (!ignoreParentClass) {
  46495. _super.prototype._updateCache.call(this);
  46496. }
  46497. var lockedTargetPosition = this._getLockedTargetPosition();
  46498. if (!lockedTargetPosition) {
  46499. this._cache.lockedTarget = null;
  46500. }
  46501. else {
  46502. if (!this._cache.lockedTarget) {
  46503. this._cache.lockedTarget = lockedTargetPosition.clone();
  46504. }
  46505. else {
  46506. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46507. }
  46508. }
  46509. this._cache.rotation.copyFrom(this.rotation);
  46510. if (this.rotationQuaternion)
  46511. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46512. };
  46513. // Synchronized
  46514. /** @hidden */
  46515. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46516. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46517. return false;
  46518. }
  46519. var lockedTargetPosition = this._getLockedTargetPosition();
  46520. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46521. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46522. };
  46523. // Methods
  46524. /** @hidden */
  46525. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46526. var engine = this.getEngine();
  46527. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46528. };
  46529. // Target
  46530. /** @hidden */
  46531. TargetCamera.prototype.setTarget = function (target) {
  46532. this.upVector.normalize();
  46533. if (this.position.z === target.z) {
  46534. this.position.z += BABYLON.Epsilon;
  46535. }
  46536. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46537. this._camMatrix.invert();
  46538. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46539. var vDir = target.subtract(this.position);
  46540. if (vDir.x >= 0.0) {
  46541. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46542. }
  46543. else {
  46544. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46545. }
  46546. this.rotation.z = 0;
  46547. if (isNaN(this.rotation.x)) {
  46548. this.rotation.x = 0;
  46549. }
  46550. if (isNaN(this.rotation.y)) {
  46551. this.rotation.y = 0;
  46552. }
  46553. if (isNaN(this.rotation.z)) {
  46554. this.rotation.z = 0;
  46555. }
  46556. if (this.rotationQuaternion) {
  46557. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46558. }
  46559. };
  46560. /**
  46561. * Return the current target position of the camera. This value is expressed in local space.
  46562. */
  46563. TargetCamera.prototype.getTarget = function () {
  46564. return this._currentTarget;
  46565. };
  46566. /** @hidden */
  46567. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46568. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46569. };
  46570. /** @hidden */
  46571. TargetCamera.prototype._updatePosition = function () {
  46572. if (this.parent) {
  46573. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46574. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46575. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46576. return;
  46577. }
  46578. this.position.addInPlace(this.cameraDirection);
  46579. };
  46580. /** @hidden */
  46581. TargetCamera.prototype._checkInputs = function () {
  46582. var needToMove = this._decideIfNeedsToMove();
  46583. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46584. // Move
  46585. if (needToMove) {
  46586. this._updatePosition();
  46587. }
  46588. // Rotate
  46589. if (needToRotate) {
  46590. this.rotation.x += this.cameraRotation.x;
  46591. this.rotation.y += this.cameraRotation.y;
  46592. //rotate, if quaternion is set and rotation was used
  46593. if (this.rotationQuaternion) {
  46594. var len = this.rotation.lengthSquared();
  46595. if (len) {
  46596. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46597. }
  46598. }
  46599. if (!this.noRotationConstraint) {
  46600. var limit = (Math.PI / 2) * 0.95;
  46601. if (this.rotation.x > limit)
  46602. this.rotation.x = limit;
  46603. if (this.rotation.x < -limit)
  46604. this.rotation.x = -limit;
  46605. }
  46606. }
  46607. // Inertia
  46608. if (needToMove) {
  46609. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46610. this.cameraDirection.x = 0;
  46611. }
  46612. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46613. this.cameraDirection.y = 0;
  46614. }
  46615. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46616. this.cameraDirection.z = 0;
  46617. }
  46618. this.cameraDirection.scaleInPlace(this.inertia);
  46619. }
  46620. if (needToRotate) {
  46621. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46622. this.cameraRotation.x = 0;
  46623. }
  46624. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46625. this.cameraRotation.y = 0;
  46626. }
  46627. this.cameraRotation.scaleInPlace(this.inertia);
  46628. }
  46629. _super.prototype._checkInputs.call(this);
  46630. };
  46631. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46632. if (this.rotationQuaternion) {
  46633. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46634. }
  46635. else {
  46636. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46637. }
  46638. };
  46639. /**
  46640. * 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)
  46641. * @returns the current camera
  46642. */
  46643. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46644. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46645. return this;
  46646. };
  46647. /** @hidden */
  46648. TargetCamera.prototype._getViewMatrix = function () {
  46649. if (this.lockedTarget) {
  46650. this.setTarget(this._getLockedTargetPosition());
  46651. }
  46652. // Compute
  46653. this._updateCameraRotationMatrix();
  46654. // Apply the changed rotation to the upVector.
  46655. if (this._cachedRotationZ != this.rotation.z) {
  46656. this._rotateUpVectorWithCameraRotationMatrix();
  46657. this._cachedRotationZ = this.rotation.z;
  46658. }
  46659. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46660. // Computing target and final matrix
  46661. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46662. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46663. return this._viewMatrix;
  46664. };
  46665. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46666. if (this.parent) {
  46667. var parentWorldMatrix = this.parent.getWorldMatrix();
  46668. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46669. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46670. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46671. this._markSyncedWithParent();
  46672. }
  46673. else {
  46674. this._globalPosition.copyFrom(position);
  46675. this._globalCurrentTarget.copyFrom(target);
  46676. this._globalCurrentUpVector.copyFrom(up);
  46677. }
  46678. if (this.getScene().useRightHandedSystem) {
  46679. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46680. }
  46681. else {
  46682. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46683. }
  46684. };
  46685. /**
  46686. * @override
  46687. * Override Camera.createRigCamera
  46688. */
  46689. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46690. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46691. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46692. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46693. if (!this.rotationQuaternion) {
  46694. this.rotationQuaternion = new BABYLON.Quaternion();
  46695. }
  46696. rigCamera._cameraRigParams = {};
  46697. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46698. }
  46699. return rigCamera;
  46700. }
  46701. return null;
  46702. };
  46703. /**
  46704. * @hidden
  46705. * @override
  46706. * Override Camera._updateRigCameras
  46707. */
  46708. TargetCamera.prototype._updateRigCameras = function () {
  46709. var camLeft = this._rigCameras[0];
  46710. var camRight = this._rigCameras[1];
  46711. switch (this.cameraRigMode) {
  46712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46714. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46715. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46716. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46717. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46718. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46719. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46720. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46721. camLeft.setTarget(this.getTarget());
  46722. camRight.setTarget(this.getTarget());
  46723. break;
  46724. case BABYLON.Camera.RIG_MODE_VR:
  46725. if (camLeft.rotationQuaternion) {
  46726. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46727. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46728. }
  46729. else {
  46730. camLeft.rotation.copyFrom(this.rotation);
  46731. camRight.rotation.copyFrom(this.rotation);
  46732. }
  46733. camLeft.position.copyFrom(this.position);
  46734. camRight.position.copyFrom(this.position);
  46735. break;
  46736. }
  46737. _super.prototype._updateRigCameras.call(this);
  46738. };
  46739. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46740. if (!this._rigCamTransformMatrix) {
  46741. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46742. }
  46743. var target = this.getTarget();
  46744. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46745. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46746. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46747. };
  46748. TargetCamera.prototype.getClassName = function () {
  46749. return "TargetCamera";
  46750. };
  46751. __decorate([
  46752. BABYLON.serializeAsVector3()
  46753. ], TargetCamera.prototype, "rotation", void 0);
  46754. __decorate([
  46755. BABYLON.serialize()
  46756. ], TargetCamera.prototype, "speed", void 0);
  46757. __decorate([
  46758. BABYLON.serializeAsMeshReference("lockedTargetId")
  46759. ], TargetCamera.prototype, "lockedTarget", void 0);
  46760. return TargetCamera;
  46761. }(BABYLON.Camera));
  46762. BABYLON.TargetCamera = TargetCamera;
  46763. })(BABYLON || (BABYLON = {}));
  46764. //# sourceMappingURL=babylon.targetCamera.js.map
  46765. var BABYLON;
  46766. (function (BABYLON) {
  46767. var FreeCameraMouseInput = /** @class */ (function () {
  46768. function FreeCameraMouseInput(touchEnabled) {
  46769. if (touchEnabled === void 0) { touchEnabled = true; }
  46770. this.touchEnabled = touchEnabled;
  46771. this.buttons = [0, 1, 2];
  46772. this.angularSensibility = 2000.0;
  46773. this.previousPosition = null;
  46774. }
  46775. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46776. var _this = this;
  46777. var engine = this.camera.getEngine();
  46778. if (!this._pointerInput) {
  46779. this._pointerInput = function (p, s) {
  46780. var evt = p.event;
  46781. if (engine.isInVRExclusivePointerMode) {
  46782. return;
  46783. }
  46784. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46785. return;
  46786. }
  46787. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46788. return;
  46789. }
  46790. var srcElement = (evt.srcElement || evt.target);
  46791. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46792. try {
  46793. srcElement.setPointerCapture(evt.pointerId);
  46794. }
  46795. catch (e) {
  46796. //Nothing to do with the error. Execution will continue.
  46797. }
  46798. _this.previousPosition = {
  46799. x: evt.clientX,
  46800. y: evt.clientY
  46801. };
  46802. if (!noPreventDefault) {
  46803. evt.preventDefault();
  46804. element.focus();
  46805. }
  46806. }
  46807. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46808. try {
  46809. srcElement.releasePointerCapture(evt.pointerId);
  46810. }
  46811. catch (e) {
  46812. //Nothing to do with the error.
  46813. }
  46814. _this.previousPosition = null;
  46815. if (!noPreventDefault) {
  46816. evt.preventDefault();
  46817. }
  46818. }
  46819. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46820. if (!_this.previousPosition || engine.isPointerLock) {
  46821. return;
  46822. }
  46823. var offsetX = evt.clientX - _this.previousPosition.x;
  46824. if (_this.camera.getScene().useRightHandedSystem)
  46825. offsetX *= -1;
  46826. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46827. offsetX *= -1;
  46828. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46829. var offsetY = evt.clientY - _this.previousPosition.y;
  46830. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46831. _this.previousPosition = {
  46832. x: evt.clientX,
  46833. y: evt.clientY
  46834. };
  46835. if (!noPreventDefault) {
  46836. evt.preventDefault();
  46837. }
  46838. }
  46839. };
  46840. }
  46841. this._onMouseMove = function (evt) {
  46842. if (!engine.isPointerLock) {
  46843. return;
  46844. }
  46845. if (engine.isInVRExclusivePointerMode) {
  46846. return;
  46847. }
  46848. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46849. if (_this.camera.getScene().useRightHandedSystem)
  46850. offsetX *= -1;
  46851. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46852. offsetX *= -1;
  46853. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46854. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46855. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46856. _this.previousPosition = null;
  46857. if (!noPreventDefault) {
  46858. evt.preventDefault();
  46859. }
  46860. };
  46861. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46862. element.addEventListener("mousemove", this._onMouseMove, false);
  46863. };
  46864. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46865. if (this._observer && element) {
  46866. this.camera.getScene().onPointerObservable.remove(this._observer);
  46867. if (this._onMouseMove) {
  46868. element.removeEventListener("mousemove", this._onMouseMove);
  46869. }
  46870. this._observer = null;
  46871. this._onMouseMove = null;
  46872. this.previousPosition = null;
  46873. }
  46874. };
  46875. FreeCameraMouseInput.prototype.getClassName = function () {
  46876. return "FreeCameraMouseInput";
  46877. };
  46878. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46879. return "mouse";
  46880. };
  46881. __decorate([
  46882. BABYLON.serialize()
  46883. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46887. return FreeCameraMouseInput;
  46888. }());
  46889. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46890. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46891. })(BABYLON || (BABYLON = {}));
  46892. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46893. var BABYLON;
  46894. (function (BABYLON) {
  46895. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46896. function FreeCameraKeyboardMoveInput() {
  46897. this._keys = new Array();
  46898. this.keysUp = [38];
  46899. this.keysDown = [40];
  46900. this.keysLeft = [37];
  46901. this.keysRight = [39];
  46902. }
  46903. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46904. var _this = this;
  46905. if (this._onCanvasBlurObserver) {
  46906. return;
  46907. }
  46908. this._scene = this.camera.getScene();
  46909. this._engine = this._scene.getEngine();
  46910. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46911. _this._keys = [];
  46912. });
  46913. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46914. var evt = info.event;
  46915. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46916. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46917. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46918. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46919. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46920. var index = _this._keys.indexOf(evt.keyCode);
  46921. if (index === -1) {
  46922. _this._keys.push(evt.keyCode);
  46923. }
  46924. if (!noPreventDefault) {
  46925. evt.preventDefault();
  46926. }
  46927. }
  46928. }
  46929. else {
  46930. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46931. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46932. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46933. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46934. var index = _this._keys.indexOf(evt.keyCode);
  46935. if (index >= 0) {
  46936. _this._keys.splice(index, 1);
  46937. }
  46938. if (!noPreventDefault) {
  46939. evt.preventDefault();
  46940. }
  46941. }
  46942. }
  46943. });
  46944. };
  46945. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46946. if (this._scene) {
  46947. if (this._onKeyboardObserver) {
  46948. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46949. }
  46950. if (this._onCanvasBlurObserver) {
  46951. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46952. }
  46953. this._onKeyboardObserver = null;
  46954. this._onCanvasBlurObserver = null;
  46955. }
  46956. this._keys = [];
  46957. };
  46958. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46959. if (this._onKeyboardObserver) {
  46960. var camera = this.camera;
  46961. // Keyboard
  46962. for (var index = 0; index < this._keys.length; index++) {
  46963. var keyCode = this._keys[index];
  46964. var speed = camera._computeLocalCameraSpeed();
  46965. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46966. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46967. }
  46968. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46969. camera._localDirection.copyFromFloats(0, 0, speed);
  46970. }
  46971. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46972. camera._localDirection.copyFromFloats(speed, 0, 0);
  46973. }
  46974. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46975. camera._localDirection.copyFromFloats(0, 0, -speed);
  46976. }
  46977. if (camera.getScene().useRightHandedSystem) {
  46978. camera._localDirection.z *= -1;
  46979. }
  46980. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46981. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46982. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46983. }
  46984. }
  46985. };
  46986. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46987. return "FreeCameraKeyboardMoveInput";
  46988. };
  46989. /** @hidden */
  46990. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46991. this._keys = [];
  46992. };
  46993. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46994. return "keyboard";
  46995. };
  46996. __decorate([
  46997. BABYLON.serialize()
  46998. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46999. __decorate([
  47000. BABYLON.serialize()
  47001. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47002. __decorate([
  47003. BABYLON.serialize()
  47004. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47005. __decorate([
  47006. BABYLON.serialize()
  47007. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47008. return FreeCameraKeyboardMoveInput;
  47009. }());
  47010. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47011. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47012. })(BABYLON || (BABYLON = {}));
  47013. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47014. var BABYLON;
  47015. (function (BABYLON) {
  47016. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47017. __extends(FreeCameraInputsManager, _super);
  47018. function FreeCameraInputsManager(camera) {
  47019. return _super.call(this, camera) || this;
  47020. }
  47021. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47022. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47023. return this;
  47024. };
  47025. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47026. if (touchEnabled === void 0) { touchEnabled = true; }
  47027. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47028. return this;
  47029. };
  47030. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47031. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47032. return this;
  47033. };
  47034. FreeCameraInputsManager.prototype.addTouch = function () {
  47035. this.add(new BABYLON.FreeCameraTouchInput());
  47036. return this;
  47037. };
  47038. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47039. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47040. return this;
  47041. };
  47042. return FreeCameraInputsManager;
  47043. }(BABYLON.CameraInputsManager));
  47044. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47045. })(BABYLON || (BABYLON = {}));
  47046. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47047. var BABYLON;
  47048. (function (BABYLON) {
  47049. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47050. // Forcing to use the Universal camera
  47051. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47052. });
  47053. var FreeCamera = /** @class */ (function (_super) {
  47054. __extends(FreeCamera, _super);
  47055. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47056. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47057. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47058. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47059. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47060. _this.checkCollisions = false;
  47061. _this.applyGravity = false;
  47062. _this._needMoveForGravity = false;
  47063. _this._oldPosition = BABYLON.Vector3.Zero();
  47064. _this._diffPosition = BABYLON.Vector3.Zero();
  47065. _this._newPosition = BABYLON.Vector3.Zero();
  47066. // Collisions
  47067. _this._collisionMask = -1;
  47068. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47069. if (collidedMesh === void 0) { collidedMesh = null; }
  47070. //TODO move this to the collision coordinator!
  47071. if (_this.getScene().workerCollisions)
  47072. newPosition.multiplyInPlace(_this._collider._radius);
  47073. var updatePosition = function (newPos) {
  47074. _this._newPosition.copyFrom(newPos);
  47075. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47076. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47077. _this.position.addInPlace(_this._diffPosition);
  47078. if (_this.onCollide && collidedMesh) {
  47079. _this.onCollide(collidedMesh);
  47080. }
  47081. }
  47082. };
  47083. updatePosition(newPosition);
  47084. };
  47085. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47086. _this.inputs.addKeyboard().addMouse();
  47087. return _this;
  47088. }
  47089. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47090. //-- begin properties for backward compatibility for inputs
  47091. /**
  47092. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47093. * Higher values reduce sensitivity.
  47094. */
  47095. get: function () {
  47096. var mouse = this.inputs.attached["mouse"];
  47097. if (mouse)
  47098. return mouse.angularSensibility;
  47099. return 0;
  47100. },
  47101. /**
  47102. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47103. * Higher values reduce sensitivity.
  47104. */
  47105. set: function (value) {
  47106. var mouse = this.inputs.attached["mouse"];
  47107. if (mouse)
  47108. mouse.angularSensibility = value;
  47109. },
  47110. enumerable: true,
  47111. configurable: true
  47112. });
  47113. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47114. get: function () {
  47115. var keyboard = this.inputs.attached["keyboard"];
  47116. if (keyboard)
  47117. return keyboard.keysUp;
  47118. return [];
  47119. },
  47120. set: function (value) {
  47121. var keyboard = this.inputs.attached["keyboard"];
  47122. if (keyboard)
  47123. keyboard.keysUp = value;
  47124. },
  47125. enumerable: true,
  47126. configurable: true
  47127. });
  47128. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47129. get: function () {
  47130. var keyboard = this.inputs.attached["keyboard"];
  47131. if (keyboard)
  47132. return keyboard.keysDown;
  47133. return [];
  47134. },
  47135. set: function (value) {
  47136. var keyboard = this.inputs.attached["keyboard"];
  47137. if (keyboard)
  47138. keyboard.keysDown = value;
  47139. },
  47140. enumerable: true,
  47141. configurable: true
  47142. });
  47143. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47144. get: function () {
  47145. var keyboard = this.inputs.attached["keyboard"];
  47146. if (keyboard)
  47147. return keyboard.keysLeft;
  47148. return [];
  47149. },
  47150. set: function (value) {
  47151. var keyboard = this.inputs.attached["keyboard"];
  47152. if (keyboard)
  47153. keyboard.keysLeft = value;
  47154. },
  47155. enumerable: true,
  47156. configurable: true
  47157. });
  47158. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47159. get: function () {
  47160. var keyboard = this.inputs.attached["keyboard"];
  47161. if (keyboard)
  47162. return keyboard.keysRight;
  47163. return [];
  47164. },
  47165. set: function (value) {
  47166. var keyboard = this.inputs.attached["keyboard"];
  47167. if (keyboard)
  47168. keyboard.keysRight = value;
  47169. },
  47170. enumerable: true,
  47171. configurable: true
  47172. });
  47173. // Controls
  47174. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47175. this.inputs.attachElement(element, noPreventDefault);
  47176. };
  47177. FreeCamera.prototype.detachControl = function (element) {
  47178. this.inputs.detachElement(element);
  47179. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47180. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47181. };
  47182. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47183. get: function () {
  47184. return this._collisionMask;
  47185. },
  47186. set: function (mask) {
  47187. this._collisionMask = !isNaN(mask) ? mask : -1;
  47188. },
  47189. enumerable: true,
  47190. configurable: true
  47191. });
  47192. /** @hidden */
  47193. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47194. var globalPosition;
  47195. if (this.parent) {
  47196. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47197. }
  47198. else {
  47199. globalPosition = this.position;
  47200. }
  47201. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47202. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47203. if (!this._collider) {
  47204. this._collider = new BABYLON.Collider();
  47205. }
  47206. this._collider._radius = this.ellipsoid;
  47207. this._collider.collisionMask = this._collisionMask;
  47208. //no need for clone, as long as gravity is not on.
  47209. var actualDisplacement = displacement;
  47210. //add gravity to the direction to prevent the dual-collision checking
  47211. if (this.applyGravity) {
  47212. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47213. actualDisplacement = displacement.add(this.getScene().gravity);
  47214. }
  47215. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47216. };
  47217. /** @hidden */
  47218. FreeCamera.prototype._checkInputs = function () {
  47219. if (!this._localDirection) {
  47220. this._localDirection = BABYLON.Vector3.Zero();
  47221. this._transformedDirection = BABYLON.Vector3.Zero();
  47222. }
  47223. this.inputs.checkInputs();
  47224. _super.prototype._checkInputs.call(this);
  47225. };
  47226. /** @hidden */
  47227. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47228. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47229. };
  47230. /** @hidden */
  47231. FreeCamera.prototype._updatePosition = function () {
  47232. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47233. this._collideWithWorld(this.cameraDirection);
  47234. }
  47235. else {
  47236. _super.prototype._updatePosition.call(this);
  47237. }
  47238. };
  47239. FreeCamera.prototype.dispose = function () {
  47240. this.inputs.clear();
  47241. _super.prototype.dispose.call(this);
  47242. };
  47243. FreeCamera.prototype.getClassName = function () {
  47244. return "FreeCamera";
  47245. };
  47246. __decorate([
  47247. BABYLON.serializeAsVector3()
  47248. ], FreeCamera.prototype, "ellipsoid", void 0);
  47249. __decorate([
  47250. BABYLON.serializeAsVector3()
  47251. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47252. __decorate([
  47253. BABYLON.serialize()
  47254. ], FreeCamera.prototype, "checkCollisions", void 0);
  47255. __decorate([
  47256. BABYLON.serialize()
  47257. ], FreeCamera.prototype, "applyGravity", void 0);
  47258. return FreeCamera;
  47259. }(BABYLON.TargetCamera));
  47260. BABYLON.FreeCamera = FreeCamera;
  47261. })(BABYLON || (BABYLON = {}));
  47262. //# sourceMappingURL=babylon.freeCamera.js.map
  47263. var BABYLON;
  47264. (function (BABYLON) {
  47265. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47266. function ArcRotateCameraKeyboardMoveInput() {
  47267. this._keys = new Array();
  47268. this.keysUp = [38];
  47269. this.keysDown = [40];
  47270. this.keysLeft = [37];
  47271. this.keysRight = [39];
  47272. this.keysReset = [220];
  47273. this.panningSensibility = 50.0;
  47274. this.zoomingSensibility = 25.0;
  47275. this.useAltToZoom = true;
  47276. }
  47277. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47278. var _this = this;
  47279. if (this._onCanvasBlurObserver) {
  47280. return;
  47281. }
  47282. this._scene = this.camera.getScene();
  47283. this._engine = this._scene.getEngine();
  47284. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47285. _this._keys = [];
  47286. });
  47287. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47288. var evt = info.event;
  47289. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47290. _this._ctrlPressed = evt.ctrlKey;
  47291. _this._altPressed = evt.altKey;
  47292. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47293. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47294. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47295. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47296. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47297. var index = _this._keys.indexOf(evt.keyCode);
  47298. if (index === -1) {
  47299. _this._keys.push(evt.keyCode);
  47300. }
  47301. if (evt.preventDefault) {
  47302. if (!noPreventDefault) {
  47303. evt.preventDefault();
  47304. }
  47305. }
  47306. }
  47307. }
  47308. else {
  47309. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47310. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47311. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47312. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47313. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47314. var index = _this._keys.indexOf(evt.keyCode);
  47315. if (index >= 0) {
  47316. _this._keys.splice(index, 1);
  47317. }
  47318. if (evt.preventDefault) {
  47319. if (!noPreventDefault) {
  47320. evt.preventDefault();
  47321. }
  47322. }
  47323. }
  47324. }
  47325. });
  47326. };
  47327. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47328. if (this._scene) {
  47329. if (this._onKeyboardObserver) {
  47330. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47331. }
  47332. if (this._onCanvasBlurObserver) {
  47333. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47334. }
  47335. this._onKeyboardObserver = null;
  47336. this._onCanvasBlurObserver = null;
  47337. }
  47338. this._keys = [];
  47339. };
  47340. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47341. if (this._onKeyboardObserver) {
  47342. var camera = this.camera;
  47343. for (var index = 0; index < this._keys.length; index++) {
  47344. var keyCode = this._keys[index];
  47345. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47346. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47347. camera.inertialPanningX -= 1 / this.panningSensibility;
  47348. }
  47349. else {
  47350. camera.inertialAlphaOffset -= 0.01;
  47351. }
  47352. }
  47353. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47354. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47355. camera.inertialPanningY += 1 / this.panningSensibility;
  47356. }
  47357. else if (this._altPressed && this.useAltToZoom) {
  47358. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47359. }
  47360. else {
  47361. camera.inertialBetaOffset -= 0.01;
  47362. }
  47363. }
  47364. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47365. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47366. camera.inertialPanningX += 1 / this.panningSensibility;
  47367. }
  47368. else {
  47369. camera.inertialAlphaOffset += 0.01;
  47370. }
  47371. }
  47372. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47373. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47374. camera.inertialPanningY -= 1 / this.panningSensibility;
  47375. }
  47376. else if (this._altPressed && this.useAltToZoom) {
  47377. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47378. }
  47379. else {
  47380. camera.inertialBetaOffset += 0.01;
  47381. }
  47382. }
  47383. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47384. camera.restoreState();
  47385. }
  47386. }
  47387. }
  47388. };
  47389. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47390. return "ArcRotateCameraKeyboardMoveInput";
  47391. };
  47392. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47393. return "keyboard";
  47394. };
  47395. __decorate([
  47396. BABYLON.serialize()
  47397. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47398. __decorate([
  47399. BABYLON.serialize()
  47400. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47401. __decorate([
  47402. BABYLON.serialize()
  47403. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47404. __decorate([
  47405. BABYLON.serialize()
  47406. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47407. __decorate([
  47408. BABYLON.serialize()
  47409. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47410. __decorate([
  47411. BABYLON.serialize()
  47412. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47413. __decorate([
  47414. BABYLON.serialize()
  47415. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47416. __decorate([
  47417. BABYLON.serialize()
  47418. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47419. return ArcRotateCameraKeyboardMoveInput;
  47420. }());
  47421. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47422. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47423. })(BABYLON || (BABYLON = {}));
  47424. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47425. var BABYLON;
  47426. (function (BABYLON) {
  47427. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47428. function ArcRotateCameraMouseWheelInput() {
  47429. this.wheelPrecision = 3.0;
  47430. /**
  47431. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47432. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47433. */
  47434. this.wheelDeltaPercentage = 0;
  47435. }
  47436. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47437. var _this = this;
  47438. this._wheel = function (p, s) {
  47439. //sanity check - this should be a PointerWheel event.
  47440. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47441. return;
  47442. var event = p.event;
  47443. var delta = 0;
  47444. if (event.wheelDelta) {
  47445. if (_this.wheelDeltaPercentage) {
  47446. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47447. if (event.wheelDelta > 0) {
  47448. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47449. }
  47450. else {
  47451. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47452. }
  47453. }
  47454. else {
  47455. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47456. }
  47457. }
  47458. else if (event.detail) {
  47459. delta = -event.detail / _this.wheelPrecision;
  47460. }
  47461. if (delta)
  47462. _this.camera.inertialRadiusOffset += delta;
  47463. if (event.preventDefault) {
  47464. if (!noPreventDefault) {
  47465. event.preventDefault();
  47466. }
  47467. }
  47468. };
  47469. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47470. };
  47471. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47472. if (this._observer && element) {
  47473. this.camera.getScene().onPointerObservable.remove(this._observer);
  47474. this._observer = null;
  47475. this._wheel = null;
  47476. }
  47477. };
  47478. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47479. return "ArcRotateCameraMouseWheelInput";
  47480. };
  47481. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47482. return "mousewheel";
  47483. };
  47484. __decorate([
  47485. BABYLON.serialize()
  47486. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47487. __decorate([
  47488. BABYLON.serialize()
  47489. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47490. return ArcRotateCameraMouseWheelInput;
  47491. }());
  47492. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47493. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47494. })(BABYLON || (BABYLON = {}));
  47495. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47496. var BABYLON;
  47497. (function (BABYLON) {
  47498. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47499. function ArcRotateCameraPointersInput() {
  47500. this.buttons = [0, 1, 2];
  47501. this.angularSensibilityX = 1000.0;
  47502. this.angularSensibilityY = 1000.0;
  47503. this.pinchPrecision = 12.0;
  47504. /**
  47505. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47506. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47507. */
  47508. this.pinchDeltaPercentage = 0;
  47509. this.panningSensibility = 1000.0;
  47510. this.multiTouchPanning = true;
  47511. this.multiTouchPanAndZoom = true;
  47512. this._isPanClick = false;
  47513. this.pinchInwards = true;
  47514. }
  47515. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47516. var _this = this;
  47517. var engine = this.camera.getEngine();
  47518. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47519. var pointA = null;
  47520. var pointB = null;
  47521. var previousPinchSquaredDistance = 0;
  47522. var initialDistance = 0;
  47523. var twoFingerActivityCount = 0;
  47524. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47525. this._pointerInput = function (p, s) {
  47526. var evt = p.event;
  47527. var isTouch = p.event.pointerType === "touch";
  47528. if (engine.isInVRExclusivePointerMode) {
  47529. return;
  47530. }
  47531. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47532. return;
  47533. }
  47534. var srcElement = (evt.srcElement || evt.target);
  47535. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47536. try {
  47537. srcElement.setPointerCapture(evt.pointerId);
  47538. }
  47539. catch (e) {
  47540. //Nothing to do with the error. Execution will continue.
  47541. }
  47542. // Manage panning with pan button click
  47543. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47544. // manage pointers
  47545. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47546. if (pointA === null) {
  47547. pointA = cacheSoloPointer;
  47548. }
  47549. else if (pointB === null) {
  47550. pointB = cacheSoloPointer;
  47551. }
  47552. if (!noPreventDefault) {
  47553. evt.preventDefault();
  47554. element.focus();
  47555. }
  47556. }
  47557. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47558. _this.camera.restoreState();
  47559. }
  47560. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47561. try {
  47562. srcElement.releasePointerCapture(evt.pointerId);
  47563. }
  47564. catch (e) {
  47565. //Nothing to do with the error.
  47566. }
  47567. cacheSoloPointer = null;
  47568. previousPinchSquaredDistance = 0;
  47569. previousMultiTouchPanPosition.isPaning = false;
  47570. previousMultiTouchPanPosition.isPinching = false;
  47571. twoFingerActivityCount = 0;
  47572. initialDistance = 0;
  47573. if (!isTouch) {
  47574. pointB = null; // Mouse and pen are mono pointer
  47575. }
  47576. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47577. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47578. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47579. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47580. if (engine._badOS) {
  47581. pointA = pointB = null;
  47582. }
  47583. else {
  47584. //only remove the impacted pointer in case of multitouch allowing on most
  47585. //platforms switching from rotate to zoom and pan seamlessly.
  47586. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47587. pointA = pointB;
  47588. pointB = null;
  47589. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47590. }
  47591. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47592. pointB = null;
  47593. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47594. }
  47595. else {
  47596. pointA = pointB = null;
  47597. }
  47598. }
  47599. if (!noPreventDefault) {
  47600. evt.preventDefault();
  47601. }
  47602. }
  47603. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47604. if (!noPreventDefault) {
  47605. evt.preventDefault();
  47606. }
  47607. // One button down
  47608. if (pointA && pointB === null && cacheSoloPointer) {
  47609. if (_this.panningSensibility !== 0 &&
  47610. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47611. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47612. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47613. }
  47614. else {
  47615. var offsetX = evt.clientX - cacheSoloPointer.x;
  47616. var offsetY = evt.clientY - cacheSoloPointer.y;
  47617. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47618. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47619. }
  47620. cacheSoloPointer.x = evt.clientX;
  47621. cacheSoloPointer.y = evt.clientY;
  47622. }
  47623. // Two buttons down: pinch/pan
  47624. else if (pointA && pointB) {
  47625. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47626. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47627. ed.x = evt.clientX;
  47628. ed.y = evt.clientY;
  47629. var direction = _this.pinchInwards ? 1 : -1;
  47630. var distX = pointA.x - pointB.x;
  47631. var distY = pointA.y - pointB.y;
  47632. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47633. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47634. if (previousPinchSquaredDistance === 0) {
  47635. initialDistance = pinchDistance;
  47636. previousPinchSquaredDistance = pinchSquaredDistance;
  47637. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47638. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47639. return;
  47640. }
  47641. if (_this.multiTouchPanAndZoom) {
  47642. if (_this.pinchDeltaPercentage) {
  47643. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47644. }
  47645. else {
  47646. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47647. (_this.pinchPrecision *
  47648. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47649. direction);
  47650. }
  47651. if (_this.panningSensibility !== 0) {
  47652. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47653. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47654. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47655. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47656. previousMultiTouchPanPosition.x = pointersCenterX;
  47657. previousMultiTouchPanPosition.y = pointersCenterY;
  47658. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47659. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47660. }
  47661. }
  47662. else {
  47663. twoFingerActivityCount++;
  47664. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47665. if (_this.pinchDeltaPercentage) {
  47666. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47667. }
  47668. else {
  47669. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47670. (_this.pinchPrecision *
  47671. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47672. direction);
  47673. }
  47674. previousMultiTouchPanPosition.isPaning = false;
  47675. previousMultiTouchPanPosition.isPinching = true;
  47676. }
  47677. else {
  47678. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47679. if (!previousMultiTouchPanPosition.isPaning) {
  47680. previousMultiTouchPanPosition.isPaning = true;
  47681. previousMultiTouchPanPosition.isPinching = false;
  47682. previousMultiTouchPanPosition.x = ed.x;
  47683. previousMultiTouchPanPosition.y = ed.y;
  47684. return;
  47685. }
  47686. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47687. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47688. }
  47689. }
  47690. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47691. previousMultiTouchPanPosition.x = ed.x;
  47692. previousMultiTouchPanPosition.y = ed.y;
  47693. }
  47694. }
  47695. previousPinchSquaredDistance = pinchSquaredDistance;
  47696. }
  47697. }
  47698. };
  47699. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47700. this._onContextMenu = function (evt) {
  47701. evt.preventDefault();
  47702. };
  47703. if (!this.camera._useCtrlForPanning) {
  47704. element.addEventListener("contextmenu", this._onContextMenu, false);
  47705. }
  47706. this._onLostFocus = function () {
  47707. //this._keys = [];
  47708. pointA = pointB = null;
  47709. previousPinchSquaredDistance = 0;
  47710. previousMultiTouchPanPosition.isPaning = false;
  47711. previousMultiTouchPanPosition.isPinching = false;
  47712. twoFingerActivityCount = 0;
  47713. cacheSoloPointer = null;
  47714. initialDistance = 0;
  47715. };
  47716. this._onMouseMove = function (evt) {
  47717. if (!engine.isPointerLock) {
  47718. return;
  47719. }
  47720. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47721. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47722. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47723. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47724. if (!noPreventDefault) {
  47725. evt.preventDefault();
  47726. }
  47727. };
  47728. this._onGestureStart = function (e) {
  47729. if (window.MSGesture === undefined) {
  47730. return;
  47731. }
  47732. if (!_this._MSGestureHandler) {
  47733. _this._MSGestureHandler = new MSGesture();
  47734. _this._MSGestureHandler.target = element;
  47735. }
  47736. _this._MSGestureHandler.addPointer(e.pointerId);
  47737. };
  47738. this._onGesture = function (e) {
  47739. _this.camera.radius *= e.scale;
  47740. if (e.preventDefault) {
  47741. if (!noPreventDefault) {
  47742. e.stopPropagation();
  47743. e.preventDefault();
  47744. }
  47745. }
  47746. };
  47747. element.addEventListener("mousemove", this._onMouseMove, false);
  47748. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47749. element.addEventListener("MSGestureChange", this._onGesture, false);
  47750. BABYLON.Tools.RegisterTopRootEvents([
  47751. { name: "blur", handler: this._onLostFocus }
  47752. ]);
  47753. };
  47754. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47755. if (this._onLostFocus) {
  47756. BABYLON.Tools.UnregisterTopRootEvents([
  47757. { name: "blur", handler: this._onLostFocus }
  47758. ]);
  47759. }
  47760. if (element && this._observer) {
  47761. this.camera.getScene().onPointerObservable.remove(this._observer);
  47762. this._observer = null;
  47763. if (this._onContextMenu) {
  47764. element.removeEventListener("contextmenu", this._onContextMenu);
  47765. }
  47766. if (this._onMouseMove) {
  47767. element.removeEventListener("mousemove", this._onMouseMove);
  47768. }
  47769. if (this._onGestureStart) {
  47770. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47771. }
  47772. if (this._onGesture) {
  47773. element.removeEventListener("MSGestureChange", this._onGesture);
  47774. }
  47775. this._isPanClick = false;
  47776. this.pinchInwards = true;
  47777. this._onMouseMove = null;
  47778. this._onGestureStart = null;
  47779. this._onGesture = null;
  47780. this._MSGestureHandler = null;
  47781. this._onLostFocus = null;
  47782. this._onContextMenu = null;
  47783. }
  47784. };
  47785. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47786. return "ArcRotateCameraPointersInput";
  47787. };
  47788. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47789. return "pointers";
  47790. };
  47791. __decorate([
  47792. BABYLON.serialize()
  47793. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47794. __decorate([
  47795. BABYLON.serialize()
  47796. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47797. __decorate([
  47798. BABYLON.serialize()
  47799. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47800. __decorate([
  47801. BABYLON.serialize()
  47802. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47803. __decorate([
  47804. BABYLON.serialize()
  47805. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47806. __decorate([
  47807. BABYLON.serialize()
  47808. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47809. __decorate([
  47810. BABYLON.serialize()
  47811. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47812. __decorate([
  47813. BABYLON.serialize()
  47814. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47815. return ArcRotateCameraPointersInput;
  47816. }());
  47817. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47818. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47819. })(BABYLON || (BABYLON = {}));
  47820. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47821. var BABYLON;
  47822. (function (BABYLON) {
  47823. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47824. __extends(ArcRotateCameraInputsManager, _super);
  47825. function ArcRotateCameraInputsManager(camera) {
  47826. return _super.call(this, camera) || this;
  47827. }
  47828. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47829. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47830. return this;
  47831. };
  47832. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47833. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47834. return this;
  47835. };
  47836. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47837. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47838. return this;
  47839. };
  47840. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47841. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47842. return this;
  47843. };
  47844. return ArcRotateCameraInputsManager;
  47845. }(BABYLON.CameraInputsManager));
  47846. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47847. })(BABYLON || (BABYLON = {}));
  47848. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47849. var BABYLON;
  47850. (function (BABYLON) {
  47851. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47852. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47853. });
  47854. var ArcRotateCamera = /** @class */ (function (_super) {
  47855. __extends(ArcRotateCamera, _super);
  47856. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47857. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47858. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47859. _this.inertialAlphaOffset = 0;
  47860. _this.inertialBetaOffset = 0;
  47861. _this.inertialRadiusOffset = 0;
  47862. _this.lowerAlphaLimit = null;
  47863. _this.upperAlphaLimit = null;
  47864. _this.lowerBetaLimit = 0.01;
  47865. _this.upperBetaLimit = Math.PI;
  47866. _this.lowerRadiusLimit = null;
  47867. _this.upperRadiusLimit = null;
  47868. _this.inertialPanningX = 0;
  47869. _this.inertialPanningY = 0;
  47870. _this.pinchToPanMaxDistance = 20;
  47871. _this.panningDistanceLimit = null;
  47872. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47873. _this.panningInertia = 0.9;
  47874. //-- end properties for backward compatibility for inputs
  47875. _this.zoomOnFactor = 1;
  47876. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47877. _this.allowUpsideDown = true;
  47878. /** @hidden */
  47879. _this._viewMatrix = new BABYLON.Matrix();
  47880. // Panning
  47881. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47882. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47883. _this.checkCollisions = false;
  47884. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47885. _this._previousPosition = BABYLON.Vector3.Zero();
  47886. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47887. _this._newPosition = BABYLON.Vector3.Zero();
  47888. _this._computationVector = BABYLON.Vector3.Zero();
  47889. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47890. if (collidedMesh === void 0) { collidedMesh = null; }
  47891. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47892. newPosition.multiplyInPlace(_this._collider._radius);
  47893. }
  47894. if (!collidedMesh) {
  47895. _this._previousPosition.copyFrom(_this.position);
  47896. }
  47897. else {
  47898. _this.setPosition(newPosition);
  47899. if (_this.onCollide) {
  47900. _this.onCollide(collidedMesh);
  47901. }
  47902. }
  47903. // Recompute because of constraints
  47904. var cosa = Math.cos(_this.alpha);
  47905. var sina = Math.sin(_this.alpha);
  47906. var cosb = Math.cos(_this.beta);
  47907. var sinb = Math.sin(_this.beta);
  47908. if (sinb === 0) {
  47909. sinb = 0.0001;
  47910. }
  47911. var target = _this._getTargetPosition();
  47912. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47913. target.addToRef(_this._computationVector, _this._newPosition);
  47914. _this.position.copyFrom(_this._newPosition);
  47915. var up = _this.upVector;
  47916. if (_this.allowUpsideDown && _this.beta < 0) {
  47917. up = up.clone();
  47918. up = up.negate();
  47919. }
  47920. _this._computeViewMatrix(_this.position, target, up);
  47921. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47922. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47923. _this._collisionTriggered = false;
  47924. };
  47925. _this._target = BABYLON.Vector3.Zero();
  47926. if (target) {
  47927. _this.setTarget(target);
  47928. }
  47929. _this.alpha = alpha;
  47930. _this.beta = beta;
  47931. _this.radius = radius;
  47932. _this.getViewMatrix();
  47933. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47934. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47935. return _this;
  47936. }
  47937. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47938. get: function () {
  47939. return this._target;
  47940. },
  47941. set: function (value) {
  47942. this.setTarget(value);
  47943. },
  47944. enumerable: true,
  47945. configurable: true
  47946. });
  47947. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47948. //-- begin properties for backward compatibility for inputs
  47949. get: function () {
  47950. var pointers = this.inputs.attached["pointers"];
  47951. if (pointers)
  47952. return pointers.angularSensibilityX;
  47953. return 0;
  47954. },
  47955. set: function (value) {
  47956. var pointers = this.inputs.attached["pointers"];
  47957. if (pointers) {
  47958. pointers.angularSensibilityX = value;
  47959. }
  47960. },
  47961. enumerable: true,
  47962. configurable: true
  47963. });
  47964. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47965. get: function () {
  47966. var pointers = this.inputs.attached["pointers"];
  47967. if (pointers)
  47968. return pointers.angularSensibilityY;
  47969. return 0;
  47970. },
  47971. set: function (value) {
  47972. var pointers = this.inputs.attached["pointers"];
  47973. if (pointers) {
  47974. pointers.angularSensibilityY = value;
  47975. }
  47976. },
  47977. enumerable: true,
  47978. configurable: true
  47979. });
  47980. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47981. get: function () {
  47982. var pointers = this.inputs.attached["pointers"];
  47983. if (pointers)
  47984. return pointers.pinchPrecision;
  47985. return 0;
  47986. },
  47987. set: function (value) {
  47988. var pointers = this.inputs.attached["pointers"];
  47989. if (pointers) {
  47990. pointers.pinchPrecision = value;
  47991. }
  47992. },
  47993. enumerable: true,
  47994. configurable: true
  47995. });
  47996. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47997. get: function () {
  47998. var pointers = this.inputs.attached["pointers"];
  47999. if (pointers)
  48000. return pointers.pinchDeltaPercentage;
  48001. return 0;
  48002. },
  48003. set: function (value) {
  48004. var pointers = this.inputs.attached["pointers"];
  48005. if (pointers) {
  48006. pointers.pinchDeltaPercentage = value;
  48007. }
  48008. },
  48009. enumerable: true,
  48010. configurable: true
  48011. });
  48012. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48013. get: function () {
  48014. var pointers = this.inputs.attached["pointers"];
  48015. if (pointers)
  48016. return pointers.panningSensibility;
  48017. return 0;
  48018. },
  48019. set: function (value) {
  48020. var pointers = this.inputs.attached["pointers"];
  48021. if (pointers) {
  48022. pointers.panningSensibility = value;
  48023. }
  48024. },
  48025. enumerable: true,
  48026. configurable: true
  48027. });
  48028. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48029. get: function () {
  48030. var keyboard = this.inputs.attached["keyboard"];
  48031. if (keyboard)
  48032. return keyboard.keysUp;
  48033. return [];
  48034. },
  48035. set: function (value) {
  48036. var keyboard = this.inputs.attached["keyboard"];
  48037. if (keyboard)
  48038. keyboard.keysUp = value;
  48039. },
  48040. enumerable: true,
  48041. configurable: true
  48042. });
  48043. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48044. get: function () {
  48045. var keyboard = this.inputs.attached["keyboard"];
  48046. if (keyboard)
  48047. return keyboard.keysDown;
  48048. return [];
  48049. },
  48050. set: function (value) {
  48051. var keyboard = this.inputs.attached["keyboard"];
  48052. if (keyboard)
  48053. keyboard.keysDown = value;
  48054. },
  48055. enumerable: true,
  48056. configurable: true
  48057. });
  48058. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48059. get: function () {
  48060. var keyboard = this.inputs.attached["keyboard"];
  48061. if (keyboard)
  48062. return keyboard.keysLeft;
  48063. return [];
  48064. },
  48065. set: function (value) {
  48066. var keyboard = this.inputs.attached["keyboard"];
  48067. if (keyboard)
  48068. keyboard.keysLeft = value;
  48069. },
  48070. enumerable: true,
  48071. configurable: true
  48072. });
  48073. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48074. get: function () {
  48075. var keyboard = this.inputs.attached["keyboard"];
  48076. if (keyboard)
  48077. return keyboard.keysRight;
  48078. return [];
  48079. },
  48080. set: function (value) {
  48081. var keyboard = this.inputs.attached["keyboard"];
  48082. if (keyboard)
  48083. keyboard.keysRight = value;
  48084. },
  48085. enumerable: true,
  48086. configurable: true
  48087. });
  48088. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48089. get: function () {
  48090. var mousewheel = this.inputs.attached["mousewheel"];
  48091. if (mousewheel)
  48092. return mousewheel.wheelPrecision;
  48093. return 0;
  48094. },
  48095. set: function (value) {
  48096. var mousewheel = this.inputs.attached["mousewheel"];
  48097. if (mousewheel)
  48098. mousewheel.wheelPrecision = value;
  48099. },
  48100. enumerable: true,
  48101. configurable: true
  48102. });
  48103. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48104. get: function () {
  48105. var mousewheel = this.inputs.attached["mousewheel"];
  48106. if (mousewheel)
  48107. return mousewheel.wheelDeltaPercentage;
  48108. return 0;
  48109. },
  48110. set: function (value) {
  48111. var mousewheel = this.inputs.attached["mousewheel"];
  48112. if (mousewheel)
  48113. mousewheel.wheelDeltaPercentage = value;
  48114. },
  48115. enumerable: true,
  48116. configurable: true
  48117. });
  48118. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48119. get: function () {
  48120. return this._bouncingBehavior;
  48121. },
  48122. enumerable: true,
  48123. configurable: true
  48124. });
  48125. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48126. get: function () {
  48127. return this._bouncingBehavior != null;
  48128. },
  48129. set: function (value) {
  48130. if (value === this.useBouncingBehavior) {
  48131. return;
  48132. }
  48133. if (value) {
  48134. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48135. this.addBehavior(this._bouncingBehavior);
  48136. }
  48137. else if (this._bouncingBehavior) {
  48138. this.removeBehavior(this._bouncingBehavior);
  48139. this._bouncingBehavior = null;
  48140. }
  48141. },
  48142. enumerable: true,
  48143. configurable: true
  48144. });
  48145. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48146. get: function () {
  48147. return this._framingBehavior;
  48148. },
  48149. enumerable: true,
  48150. configurable: true
  48151. });
  48152. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48153. get: function () {
  48154. return this._framingBehavior != null;
  48155. },
  48156. set: function (value) {
  48157. if (value === this.useFramingBehavior) {
  48158. return;
  48159. }
  48160. if (value) {
  48161. this._framingBehavior = new BABYLON.FramingBehavior();
  48162. this.addBehavior(this._framingBehavior);
  48163. }
  48164. else if (this._framingBehavior) {
  48165. this.removeBehavior(this._framingBehavior);
  48166. this._framingBehavior = null;
  48167. }
  48168. },
  48169. enumerable: true,
  48170. configurable: true
  48171. });
  48172. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48173. get: function () {
  48174. return this._autoRotationBehavior;
  48175. },
  48176. enumerable: true,
  48177. configurable: true
  48178. });
  48179. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48180. get: function () {
  48181. return this._autoRotationBehavior != null;
  48182. },
  48183. set: function (value) {
  48184. if (value === this.useAutoRotationBehavior) {
  48185. return;
  48186. }
  48187. if (value) {
  48188. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48189. this.addBehavior(this._autoRotationBehavior);
  48190. }
  48191. else if (this._autoRotationBehavior) {
  48192. this.removeBehavior(this._autoRotationBehavior);
  48193. this._autoRotationBehavior = null;
  48194. }
  48195. },
  48196. enumerable: true,
  48197. configurable: true
  48198. });
  48199. // Cache
  48200. /** @hidden */
  48201. ArcRotateCamera.prototype._initCache = function () {
  48202. _super.prototype._initCache.call(this);
  48203. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48204. this._cache.alpha = undefined;
  48205. this._cache.beta = undefined;
  48206. this._cache.radius = undefined;
  48207. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48208. };
  48209. /** @hidden */
  48210. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48211. if (!ignoreParentClass) {
  48212. _super.prototype._updateCache.call(this);
  48213. }
  48214. this._cache._target.copyFrom(this._getTargetPosition());
  48215. this._cache.alpha = this.alpha;
  48216. this._cache.beta = this.beta;
  48217. this._cache.radius = this.radius;
  48218. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48219. };
  48220. ArcRotateCamera.prototype._getTargetPosition = function () {
  48221. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48222. var pos = this._targetHost.getAbsolutePosition();
  48223. if (this._targetBoundingCenter) {
  48224. pos.addToRef(this._targetBoundingCenter, this._target);
  48225. }
  48226. else {
  48227. this._target.copyFrom(pos);
  48228. }
  48229. }
  48230. var lockedTargetPosition = this._getLockedTargetPosition();
  48231. if (lockedTargetPosition) {
  48232. return lockedTargetPosition;
  48233. }
  48234. return this._target;
  48235. };
  48236. ArcRotateCamera.prototype.storeState = function () {
  48237. this._storedAlpha = this.alpha;
  48238. this._storedBeta = this.beta;
  48239. this._storedRadius = this.radius;
  48240. this._storedTarget = this._getTargetPosition().clone();
  48241. return _super.prototype.storeState.call(this);
  48242. };
  48243. /**
  48244. * @hidden
  48245. * Restored camera state. You must call storeState() first
  48246. */
  48247. ArcRotateCamera.prototype._restoreStateValues = function () {
  48248. if (!_super.prototype._restoreStateValues.call(this)) {
  48249. return false;
  48250. }
  48251. this.alpha = this._storedAlpha;
  48252. this.beta = this._storedBeta;
  48253. this.radius = this._storedRadius;
  48254. this.setTarget(this._storedTarget.clone());
  48255. this.inertialAlphaOffset = 0;
  48256. this.inertialBetaOffset = 0;
  48257. this.inertialRadiusOffset = 0;
  48258. this.inertialPanningX = 0;
  48259. this.inertialPanningY = 0;
  48260. return true;
  48261. };
  48262. // Synchronized
  48263. /** @hidden */
  48264. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48265. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48266. return false;
  48267. return this._cache._target.equals(this._getTargetPosition())
  48268. && this._cache.alpha === this.alpha
  48269. && this._cache.beta === this.beta
  48270. && this._cache.radius === this.radius
  48271. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48272. };
  48273. // Methods
  48274. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48275. var _this = this;
  48276. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48277. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48278. this._useCtrlForPanning = useCtrlForPanning;
  48279. this._panningMouseButton = panningMouseButton;
  48280. this.inputs.attachElement(element, noPreventDefault);
  48281. this._reset = function () {
  48282. _this.inertialAlphaOffset = 0;
  48283. _this.inertialBetaOffset = 0;
  48284. _this.inertialRadiusOffset = 0;
  48285. _this.inertialPanningX = 0;
  48286. _this.inertialPanningY = 0;
  48287. };
  48288. };
  48289. ArcRotateCamera.prototype.detachControl = function (element) {
  48290. this.inputs.detachElement(element);
  48291. if (this._reset) {
  48292. this._reset();
  48293. }
  48294. };
  48295. /** @hidden */
  48296. ArcRotateCamera.prototype._checkInputs = function () {
  48297. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48298. if (this._collisionTriggered) {
  48299. return;
  48300. }
  48301. this.inputs.checkInputs();
  48302. // Inertia
  48303. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48304. var inertialAlphaOffset = this.inertialAlphaOffset;
  48305. if (this.beta <= 0)
  48306. inertialAlphaOffset *= -1;
  48307. if (this.getScene().useRightHandedSystem)
  48308. inertialAlphaOffset *= -1;
  48309. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48310. inertialAlphaOffset *= -1;
  48311. this.alpha += inertialAlphaOffset;
  48312. this.beta += this.inertialBetaOffset;
  48313. this.radius -= this.inertialRadiusOffset;
  48314. this.inertialAlphaOffset *= this.inertia;
  48315. this.inertialBetaOffset *= this.inertia;
  48316. this.inertialRadiusOffset *= this.inertia;
  48317. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48318. this.inertialAlphaOffset = 0;
  48319. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48320. this.inertialBetaOffset = 0;
  48321. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48322. this.inertialRadiusOffset = 0;
  48323. }
  48324. // Panning inertia
  48325. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48326. if (!this._localDirection) {
  48327. this._localDirection = BABYLON.Vector3.Zero();
  48328. this._transformedDirection = BABYLON.Vector3.Zero();
  48329. }
  48330. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48331. this._localDirection.multiplyInPlace(this.panningAxis);
  48332. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48333. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48334. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48335. if (!this.panningAxis.y) {
  48336. this._transformedDirection.y = 0;
  48337. }
  48338. if (!this._targetHost) {
  48339. if (this.panningDistanceLimit) {
  48340. this._transformedDirection.addInPlace(this._target);
  48341. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48342. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48343. this._target.copyFrom(this._transformedDirection);
  48344. }
  48345. }
  48346. else {
  48347. this._target.addInPlace(this._transformedDirection);
  48348. }
  48349. }
  48350. this.inertialPanningX *= this.panningInertia;
  48351. this.inertialPanningY *= this.panningInertia;
  48352. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48353. this.inertialPanningX = 0;
  48354. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48355. this.inertialPanningY = 0;
  48356. }
  48357. // Limits
  48358. this._checkLimits();
  48359. _super.prototype._checkInputs.call(this);
  48360. };
  48361. ArcRotateCamera.prototype._checkLimits = function () {
  48362. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48363. if (this.allowUpsideDown && this.beta > Math.PI) {
  48364. this.beta = this.beta - (2 * Math.PI);
  48365. }
  48366. }
  48367. else {
  48368. if (this.beta < this.lowerBetaLimit) {
  48369. this.beta = this.lowerBetaLimit;
  48370. }
  48371. }
  48372. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48373. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48374. this.beta = this.beta + (2 * Math.PI);
  48375. }
  48376. }
  48377. else {
  48378. if (this.beta > this.upperBetaLimit) {
  48379. this.beta = this.upperBetaLimit;
  48380. }
  48381. }
  48382. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48383. this.alpha = this.lowerAlphaLimit;
  48384. }
  48385. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48386. this.alpha = this.upperAlphaLimit;
  48387. }
  48388. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48389. this.radius = this.lowerRadiusLimit;
  48390. }
  48391. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48392. this.radius = this.upperRadiusLimit;
  48393. }
  48394. };
  48395. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48396. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48397. this.radius = this._computationVector.length();
  48398. if (this.radius === 0) {
  48399. this.radius = 0.0001; // Just to avoid division by zero
  48400. }
  48401. // Alpha
  48402. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48403. if (this._computationVector.z < 0) {
  48404. this.alpha = 2 * Math.PI - this.alpha;
  48405. }
  48406. // Beta
  48407. this.beta = Math.acos(this._computationVector.y / this.radius);
  48408. this._checkLimits();
  48409. };
  48410. ArcRotateCamera.prototype.setPosition = function (position) {
  48411. if (this.position.equals(position)) {
  48412. return;
  48413. }
  48414. this.position.copyFrom(position);
  48415. this.rebuildAnglesAndRadius();
  48416. };
  48417. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48418. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48419. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48420. if (target.getBoundingInfo) {
  48421. if (toBoundingCenter) {
  48422. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48423. }
  48424. else {
  48425. this._targetBoundingCenter = null;
  48426. }
  48427. this._targetHost = target;
  48428. this._target = this._getTargetPosition();
  48429. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48430. }
  48431. else {
  48432. var newTarget = target;
  48433. var currentTarget = this._getTargetPosition();
  48434. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48435. return;
  48436. }
  48437. this._targetHost = null;
  48438. this._target = newTarget;
  48439. this._targetBoundingCenter = null;
  48440. this.onMeshTargetChangedObservable.notifyObservers(null);
  48441. }
  48442. this.rebuildAnglesAndRadius();
  48443. };
  48444. /** @hidden */
  48445. ArcRotateCamera.prototype._getViewMatrix = function () {
  48446. // Compute
  48447. var cosa = Math.cos(this.alpha);
  48448. var sina = Math.sin(this.alpha);
  48449. var cosb = Math.cos(this.beta);
  48450. var sinb = Math.sin(this.beta);
  48451. if (sinb === 0) {
  48452. sinb = 0.0001;
  48453. }
  48454. var target = this._getTargetPosition();
  48455. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48456. target.addToRef(this._computationVector, this._newPosition);
  48457. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48458. if (!this._collider) {
  48459. this._collider = new BABYLON.Collider();
  48460. }
  48461. this._collider._radius = this.collisionRadius;
  48462. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48463. this._collisionTriggered = true;
  48464. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48465. }
  48466. else {
  48467. this.position.copyFrom(this._newPosition);
  48468. var up = this.upVector;
  48469. if (this.allowUpsideDown && sinb < 0) {
  48470. up = up.clone();
  48471. up = up.negate();
  48472. }
  48473. this._computeViewMatrix(this.position, target, up);
  48474. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48475. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48476. }
  48477. this._currentTarget = target;
  48478. return this._viewMatrix;
  48479. };
  48480. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48481. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48482. meshes = meshes || this.getScene().meshes;
  48483. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48484. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48485. this.radius = distance * this.zoomOnFactor;
  48486. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48487. };
  48488. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48489. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48490. var meshesOrMinMaxVector;
  48491. var distance;
  48492. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48493. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48494. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48495. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48496. }
  48497. else { //minMaxVector and distance
  48498. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48499. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48500. distance = minMaxVectorAndDistance.distance;
  48501. }
  48502. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48503. if (!doNotUpdateMaxZ) {
  48504. this.maxZ = distance * 2;
  48505. }
  48506. };
  48507. /**
  48508. * @override
  48509. * Override Camera.createRigCamera
  48510. */
  48511. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48512. var alphaShift = 0;
  48513. switch (this.cameraRigMode) {
  48514. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48515. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48516. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48517. case BABYLON.Camera.RIG_MODE_VR:
  48518. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48519. break;
  48520. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48521. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48522. break;
  48523. }
  48524. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48525. rigCam._cameraRigParams = {};
  48526. return rigCam;
  48527. };
  48528. /**
  48529. * @hidden
  48530. * @override
  48531. * Override Camera._updateRigCameras
  48532. */
  48533. ArcRotateCamera.prototype._updateRigCameras = function () {
  48534. var camLeft = this._rigCameras[0];
  48535. var camRight = this._rigCameras[1];
  48536. camLeft.beta = camRight.beta = this.beta;
  48537. camLeft.radius = camRight.radius = this.radius;
  48538. switch (this.cameraRigMode) {
  48539. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48540. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48541. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48542. case BABYLON.Camera.RIG_MODE_VR:
  48543. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48544. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48545. break;
  48546. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48547. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48548. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48549. break;
  48550. }
  48551. _super.prototype._updateRigCameras.call(this);
  48552. };
  48553. ArcRotateCamera.prototype.dispose = function () {
  48554. this.inputs.clear();
  48555. _super.prototype.dispose.call(this);
  48556. };
  48557. ArcRotateCamera.prototype.getClassName = function () {
  48558. return "ArcRotateCamera";
  48559. };
  48560. __decorate([
  48561. BABYLON.serialize()
  48562. ], ArcRotateCamera.prototype, "alpha", void 0);
  48563. __decorate([
  48564. BABYLON.serialize()
  48565. ], ArcRotateCamera.prototype, "beta", void 0);
  48566. __decorate([
  48567. BABYLON.serialize()
  48568. ], ArcRotateCamera.prototype, "radius", void 0);
  48569. __decorate([
  48570. BABYLON.serializeAsVector3("target")
  48571. ], ArcRotateCamera.prototype, "_target", void 0);
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48575. __decorate([
  48576. BABYLON.serialize()
  48577. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48578. __decorate([
  48579. BABYLON.serialize()
  48580. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48581. __decorate([
  48582. BABYLON.serialize()
  48583. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48584. __decorate([
  48585. BABYLON.serialize()
  48586. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48587. __decorate([
  48588. BABYLON.serialize()
  48589. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48590. __decorate([
  48591. BABYLON.serialize()
  48592. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48593. __decorate([
  48594. BABYLON.serialize()
  48595. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48596. __decorate([
  48597. BABYLON.serialize()
  48598. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48599. __decorate([
  48600. BABYLON.serialize()
  48601. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48602. __decorate([
  48603. BABYLON.serialize()
  48604. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48605. __decorate([
  48606. BABYLON.serialize()
  48607. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48608. __decorate([
  48609. BABYLON.serialize()
  48610. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48611. __decorate([
  48612. BABYLON.serializeAsVector3()
  48613. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48614. __decorate([
  48615. BABYLON.serialize()
  48616. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48617. __decorate([
  48618. BABYLON.serialize()
  48619. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48620. __decorate([
  48621. BABYLON.serialize()
  48622. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48623. return ArcRotateCamera;
  48624. }(BABYLON.TargetCamera));
  48625. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48626. })(BABYLON || (BABYLON = {}));
  48627. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48628. var BABYLON;
  48629. (function (BABYLON) {
  48630. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48631. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48632. });
  48633. /**
  48634. * The HemisphericLight simulates the ambient environment light,
  48635. * so the passed direction is the light reflection direction, not the incoming direction.
  48636. */
  48637. var HemisphericLight = /** @class */ (function (_super) {
  48638. __extends(HemisphericLight, _super);
  48639. /**
  48640. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48641. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48642. * The HemisphericLight can't cast shadows.
  48643. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48644. * @param name The friendly name of the light
  48645. * @param direction The direction of the light reflection
  48646. * @param scene The scene the light belongs to
  48647. */
  48648. function HemisphericLight(name, direction, scene) {
  48649. var _this = _super.call(this, name, scene) || this;
  48650. /**
  48651. * The groundColor is the light in the opposite direction to the one specified during creation.
  48652. * 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.
  48653. */
  48654. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48655. _this.direction = direction || BABYLON.Vector3.Up();
  48656. return _this;
  48657. }
  48658. HemisphericLight.prototype._buildUniformLayout = function () {
  48659. this._uniformBuffer.addUniform("vLightData", 4);
  48660. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48661. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48662. this._uniformBuffer.addUniform("vLightGround", 3);
  48663. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48664. this._uniformBuffer.addUniform("depthValues", 2);
  48665. this._uniformBuffer.create();
  48666. };
  48667. /**
  48668. * Returns the string "HemisphericLight".
  48669. * @return The class name
  48670. */
  48671. HemisphericLight.prototype.getClassName = function () {
  48672. return "HemisphericLight";
  48673. };
  48674. /**
  48675. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48676. * Returns the updated direction.
  48677. * @param target The target the direction should point to
  48678. * @return The computed direction
  48679. */
  48680. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48681. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48682. return this.direction;
  48683. };
  48684. /**
  48685. * Returns the shadow generator associated to the light.
  48686. * @returns Always null for hemispheric lights because it does not support shadows.
  48687. */
  48688. HemisphericLight.prototype.getShadowGenerator = function () {
  48689. return null;
  48690. };
  48691. /**
  48692. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48693. * @param effect The effect to update
  48694. * @param lightIndex The index of the light in the effect to update
  48695. * @returns The hemispheric light
  48696. */
  48697. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48698. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48699. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48700. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48701. return this;
  48702. };
  48703. /**
  48704. * @hidden internal use only.
  48705. */
  48706. HemisphericLight.prototype._getWorldMatrix = function () {
  48707. if (!this._worldMatrix) {
  48708. this._worldMatrix = BABYLON.Matrix.Identity();
  48709. }
  48710. return this._worldMatrix;
  48711. };
  48712. /**
  48713. * Returns the integer 3.
  48714. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48715. */
  48716. HemisphericLight.prototype.getTypeID = function () {
  48717. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48718. };
  48719. /**
  48720. * Prepares the list of defines specific to the light type.
  48721. * @param defines the list of defines
  48722. * @param lightIndex defines the index of the light for the effect
  48723. */
  48724. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48725. defines["HEMILIGHT" + lightIndex] = true;
  48726. };
  48727. __decorate([
  48728. BABYLON.serializeAsColor3()
  48729. ], HemisphericLight.prototype, "groundColor", void 0);
  48730. __decorate([
  48731. BABYLON.serializeAsVector3()
  48732. ], HemisphericLight.prototype, "direction", void 0);
  48733. return HemisphericLight;
  48734. }(BABYLON.Light));
  48735. BABYLON.HemisphericLight = HemisphericLight;
  48736. })(BABYLON || (BABYLON = {}));
  48737. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48738. 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\nvPositionUVW=positionUpdated;\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\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*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\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#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}\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#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\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>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\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}\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#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> \noutFragColor=texture(textureSampler,vUV)*vColor;\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 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#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#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 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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\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\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\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 dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*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\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\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 int octaves;\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"};
  48739. var BABYLON;
  48740. (function (BABYLON) {
  48741. /**
  48742. * Base implementation IShadowLight
  48743. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48744. */
  48745. var ShadowLight = /** @class */ (function (_super) {
  48746. __extends(ShadowLight, _super);
  48747. function ShadowLight() {
  48748. var _this = _super !== null && _super.apply(this, arguments) || this;
  48749. _this._needProjectionMatrixCompute = true;
  48750. return _this;
  48751. }
  48752. ShadowLight.prototype._setPosition = function (value) {
  48753. this._position = value;
  48754. };
  48755. Object.defineProperty(ShadowLight.prototype, "position", {
  48756. /**
  48757. * Sets the position the shadow will be casted from. Also use as the light position for both
  48758. * point and spot lights.
  48759. */
  48760. get: function () {
  48761. return this._position;
  48762. },
  48763. /**
  48764. * Sets the position the shadow will be casted from. Also use as the light position for both
  48765. * point and spot lights.
  48766. */
  48767. set: function (value) {
  48768. this._setPosition(value);
  48769. },
  48770. enumerable: true,
  48771. configurable: true
  48772. });
  48773. ShadowLight.prototype._setDirection = function (value) {
  48774. this._direction = value;
  48775. };
  48776. Object.defineProperty(ShadowLight.prototype, "direction", {
  48777. /**
  48778. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48779. * Also use as the light direction on spot and directional lights.
  48780. */
  48781. get: function () {
  48782. return this._direction;
  48783. },
  48784. /**
  48785. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48786. * Also use as the light direction on spot and directional lights.
  48787. */
  48788. set: function (value) {
  48789. this._setDirection(value);
  48790. },
  48791. enumerable: true,
  48792. configurable: true
  48793. });
  48794. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48795. /**
  48796. * Gets the shadow projection clipping minimum z value.
  48797. */
  48798. get: function () {
  48799. return this._shadowMinZ;
  48800. },
  48801. /**
  48802. * Sets the shadow projection clipping minimum z value.
  48803. */
  48804. set: function (value) {
  48805. this._shadowMinZ = value;
  48806. this.forceProjectionMatrixCompute();
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48812. /**
  48813. * Sets the shadow projection clipping maximum z value.
  48814. */
  48815. get: function () {
  48816. return this._shadowMaxZ;
  48817. },
  48818. /**
  48819. * Gets the shadow projection clipping maximum z value.
  48820. */
  48821. set: function (value) {
  48822. this._shadowMaxZ = value;
  48823. this.forceProjectionMatrixCompute();
  48824. },
  48825. enumerable: true,
  48826. configurable: true
  48827. });
  48828. /**
  48829. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48830. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48831. */
  48832. ShadowLight.prototype.computeTransformedInformation = function () {
  48833. if (this.parent && this.parent.getWorldMatrix) {
  48834. if (!this.transformedPosition) {
  48835. this.transformedPosition = BABYLON.Vector3.Zero();
  48836. }
  48837. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48838. // In case the direction is present.
  48839. if (this.direction) {
  48840. if (!this.transformedDirection) {
  48841. this.transformedDirection = BABYLON.Vector3.Zero();
  48842. }
  48843. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48844. }
  48845. return true;
  48846. }
  48847. return false;
  48848. };
  48849. /**
  48850. * Return the depth scale used for the shadow map.
  48851. * @returns the depth scale.
  48852. */
  48853. ShadowLight.prototype.getDepthScale = function () {
  48854. return 50.0;
  48855. };
  48856. /**
  48857. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48858. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48859. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48860. */
  48861. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48862. return this.transformedDirection ? this.transformedDirection : this.direction;
  48863. };
  48864. /**
  48865. * Returns the ShadowLight absolute position in the World.
  48866. * @returns the position vector in world space
  48867. */
  48868. ShadowLight.prototype.getAbsolutePosition = function () {
  48869. return this.transformedPosition ? this.transformedPosition : this.position;
  48870. };
  48871. /**
  48872. * Sets the ShadowLight direction toward the passed target.
  48873. * @param target The point tot target in local space
  48874. * @returns the updated ShadowLight direction
  48875. */
  48876. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48877. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48878. return this.direction;
  48879. };
  48880. /**
  48881. * Returns the light rotation in euler definition.
  48882. * @returns the x y z rotation in local space.
  48883. */
  48884. ShadowLight.prototype.getRotation = function () {
  48885. this.direction.normalize();
  48886. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48887. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48888. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48889. };
  48890. /**
  48891. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48892. * @returns true if a cube texture needs to be use
  48893. */
  48894. ShadowLight.prototype.needCube = function () {
  48895. return false;
  48896. };
  48897. /**
  48898. * Detects if the projection matrix requires to be recomputed this frame.
  48899. * @returns true if it requires to be recomputed otherwise, false.
  48900. */
  48901. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48902. return this._needProjectionMatrixCompute;
  48903. };
  48904. /**
  48905. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48906. */
  48907. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48908. this._needProjectionMatrixCompute = true;
  48909. };
  48910. /**
  48911. * Get the world matrix of the sahdow lights.
  48912. * @hidden Internal Use Only
  48913. */
  48914. ShadowLight.prototype._getWorldMatrix = function () {
  48915. if (!this._worldMatrix) {
  48916. this._worldMatrix = BABYLON.Matrix.Identity();
  48917. }
  48918. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48919. return this._worldMatrix;
  48920. };
  48921. /**
  48922. * Gets the minZ used for shadow according to both the scene and the light.
  48923. * @param activeCamera The camera we are returning the min for
  48924. * @returns the depth min z
  48925. */
  48926. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48927. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48928. };
  48929. /**
  48930. * Gets the maxZ used for shadow according to both the scene and the light.
  48931. * @param activeCamera The camera we are returning the max for
  48932. * @returns the depth max z
  48933. */
  48934. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48935. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48936. };
  48937. /**
  48938. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48939. * @param matrix The materix to updated with the projection information
  48940. * @param viewMatrix The transform matrix of the light
  48941. * @param renderList The list of mesh to render in the map
  48942. * @returns The current light
  48943. */
  48944. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48945. if (this.customProjectionMatrixBuilder) {
  48946. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48947. }
  48948. else {
  48949. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48950. }
  48951. return this;
  48952. };
  48953. __decorate([
  48954. BABYLON.serializeAsVector3()
  48955. ], ShadowLight.prototype, "position", null);
  48956. __decorate([
  48957. BABYLON.serializeAsVector3()
  48958. ], ShadowLight.prototype, "direction", null);
  48959. __decorate([
  48960. BABYLON.serialize()
  48961. ], ShadowLight.prototype, "shadowMinZ", null);
  48962. __decorate([
  48963. BABYLON.serialize()
  48964. ], ShadowLight.prototype, "shadowMaxZ", null);
  48965. return ShadowLight;
  48966. }(BABYLON.Light));
  48967. BABYLON.ShadowLight = ShadowLight;
  48968. })(BABYLON || (BABYLON = {}));
  48969. //# sourceMappingURL=babylon.shadowLight.js.map
  48970. var BABYLON;
  48971. (function (BABYLON) {
  48972. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48973. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48974. });
  48975. /**
  48976. * A point light is a light defined by an unique point in world space.
  48977. * The light is emitted in every direction from this point.
  48978. * A good example of a point light is a standard light bulb.
  48979. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48980. */
  48981. var PointLight = /** @class */ (function (_super) {
  48982. __extends(PointLight, _super);
  48983. /**
  48984. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48985. * A PointLight emits the light in every direction.
  48986. * It can cast shadows.
  48987. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48988. * ```javascript
  48989. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48990. * ```
  48991. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48992. * @param name The light friendly name
  48993. * @param position The position of the point light in the scene
  48994. * @param scene The scene the lights belongs to
  48995. */
  48996. function PointLight(name, position, scene) {
  48997. var _this = _super.call(this, name, scene) || this;
  48998. _this._shadowAngle = Math.PI / 2;
  48999. _this.position = position;
  49000. return _this;
  49001. }
  49002. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49003. /**
  49004. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49005. * This specifies what angle the shadow will use to be created.
  49006. *
  49007. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49008. */
  49009. get: function () {
  49010. return this._shadowAngle;
  49011. },
  49012. /**
  49013. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49014. * This specifies what angle the shadow will use to be created.
  49015. *
  49016. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49017. */
  49018. set: function (value) {
  49019. this._shadowAngle = value;
  49020. this.forceProjectionMatrixCompute();
  49021. },
  49022. enumerable: true,
  49023. configurable: true
  49024. });
  49025. Object.defineProperty(PointLight.prototype, "direction", {
  49026. /**
  49027. * Gets the direction if it has been set.
  49028. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49029. */
  49030. get: function () {
  49031. return this._direction;
  49032. },
  49033. /**
  49034. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49035. */
  49036. set: function (value) {
  49037. var previousNeedCube = this.needCube();
  49038. this._direction = value;
  49039. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49040. this._shadowGenerator.recreateShadowMap();
  49041. }
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. /**
  49047. * Returns the string "PointLight"
  49048. * @returns the class name
  49049. */
  49050. PointLight.prototype.getClassName = function () {
  49051. return "PointLight";
  49052. };
  49053. /**
  49054. * Returns the integer 0.
  49055. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49056. */
  49057. PointLight.prototype.getTypeID = function () {
  49058. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49059. };
  49060. /**
  49061. * Specifies wether or not the shadowmap should be a cube texture.
  49062. * @returns true if the shadowmap needs to be a cube texture.
  49063. */
  49064. PointLight.prototype.needCube = function () {
  49065. return !this.direction;
  49066. };
  49067. /**
  49068. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49069. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49070. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49071. */
  49072. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49073. if (this.direction) {
  49074. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49075. }
  49076. else {
  49077. switch (faceIndex) {
  49078. case 0:
  49079. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49080. case 1:
  49081. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49082. case 2:
  49083. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49084. case 3:
  49085. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49086. case 4:
  49087. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49088. case 5:
  49089. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49090. }
  49091. }
  49092. return BABYLON.Vector3.Zero();
  49093. };
  49094. /**
  49095. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49096. * - fov = PI / 2
  49097. * - aspect ratio : 1.0
  49098. * - z-near and far equal to the active camera minZ and maxZ.
  49099. * Returns the PointLight.
  49100. */
  49101. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49102. var activeCamera = this.getScene().activeCamera;
  49103. if (!activeCamera) {
  49104. return;
  49105. }
  49106. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49107. };
  49108. PointLight.prototype._buildUniformLayout = function () {
  49109. this._uniformBuffer.addUniform("vLightData", 4);
  49110. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49111. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49112. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49113. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49114. this._uniformBuffer.addUniform("depthValues", 2);
  49115. this._uniformBuffer.create();
  49116. };
  49117. /**
  49118. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49119. * @param effect The effect to update
  49120. * @param lightIndex The index of the light in the effect to update
  49121. * @returns The point light
  49122. */
  49123. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49124. if (this.computeTransformedInformation()) {
  49125. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49126. }
  49127. else {
  49128. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49129. }
  49130. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49131. return this;
  49132. };
  49133. /**
  49134. * Prepares the list of defines specific to the light type.
  49135. * @param defines the list of defines
  49136. * @param lightIndex defines the index of the light for the effect
  49137. */
  49138. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49139. defines["POINTLIGHT" + lightIndex] = true;
  49140. };
  49141. __decorate([
  49142. BABYLON.serialize()
  49143. ], PointLight.prototype, "shadowAngle", null);
  49144. return PointLight;
  49145. }(BABYLON.ShadowLight));
  49146. BABYLON.PointLight = PointLight;
  49147. })(BABYLON || (BABYLON = {}));
  49148. //# sourceMappingURL=babylon.pointLight.js.map
  49149. var BABYLON;
  49150. (function (BABYLON) {
  49151. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49152. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49153. });
  49154. /**
  49155. * A directional light is defined by a direction (what a surprise!).
  49156. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49157. * 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.
  49158. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49159. */
  49160. var DirectionalLight = /** @class */ (function (_super) {
  49161. __extends(DirectionalLight, _super);
  49162. /**
  49163. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49164. * The directional light is emitted from everywhere in the given direction.
  49165. * It can cast shawdows.
  49166. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49167. * @param name The friendly name of the light
  49168. * @param direction The direction of the light
  49169. * @param scene The scene the light belongs to
  49170. */
  49171. function DirectionalLight(name, direction, scene) {
  49172. var _this = _super.call(this, name, scene) || this;
  49173. _this._shadowFrustumSize = 0;
  49174. _this._shadowOrthoScale = 0.1;
  49175. /**
  49176. * Automatically compute the projection matrix to best fit (including all the casters)
  49177. * on each frame.
  49178. */
  49179. _this.autoUpdateExtends = true;
  49180. // Cache
  49181. _this._orthoLeft = Number.MAX_VALUE;
  49182. _this._orthoRight = Number.MIN_VALUE;
  49183. _this._orthoTop = Number.MIN_VALUE;
  49184. _this._orthoBottom = Number.MAX_VALUE;
  49185. _this.position = direction.scale(-1.0);
  49186. _this.direction = direction;
  49187. return _this;
  49188. }
  49189. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49190. /**
  49191. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49192. */
  49193. get: function () {
  49194. return this._shadowFrustumSize;
  49195. },
  49196. /**
  49197. * Specifies a fix frustum size for the shadow generation.
  49198. */
  49199. set: function (value) {
  49200. this._shadowFrustumSize = value;
  49201. this.forceProjectionMatrixCompute();
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49207. /**
  49208. * Gets the shadow projection scale against the optimal computed one.
  49209. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49210. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49211. */
  49212. get: function () {
  49213. return this._shadowOrthoScale;
  49214. },
  49215. /**
  49216. * Sets the shadow projection scale against the optimal computed one.
  49217. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49218. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49219. */
  49220. set: function (value) {
  49221. this._shadowOrthoScale = value;
  49222. this.forceProjectionMatrixCompute();
  49223. },
  49224. enumerable: true,
  49225. configurable: true
  49226. });
  49227. /**
  49228. * Returns the string "DirectionalLight".
  49229. * @return The class name
  49230. */
  49231. DirectionalLight.prototype.getClassName = function () {
  49232. return "DirectionalLight";
  49233. };
  49234. /**
  49235. * Returns the integer 1.
  49236. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49237. */
  49238. DirectionalLight.prototype.getTypeID = function () {
  49239. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49240. };
  49241. /**
  49242. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49243. * Returns the DirectionalLight Shadow projection matrix.
  49244. */
  49245. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49246. if (this.shadowFrustumSize > 0) {
  49247. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49248. }
  49249. else {
  49250. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49251. }
  49252. };
  49253. /**
  49254. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49255. * Returns the DirectionalLight Shadow projection matrix.
  49256. */
  49257. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49258. var activeCamera = this.getScene().activeCamera;
  49259. if (!activeCamera) {
  49260. return;
  49261. }
  49262. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49263. };
  49264. /**
  49265. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49266. * Returns the DirectionalLight Shadow projection matrix.
  49267. */
  49268. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49269. var activeCamera = this.getScene().activeCamera;
  49270. if (!activeCamera) {
  49271. return;
  49272. }
  49273. // Check extends
  49274. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49275. var tempVector3 = BABYLON.Vector3.Zero();
  49276. this._orthoLeft = Number.MAX_VALUE;
  49277. this._orthoRight = Number.MIN_VALUE;
  49278. this._orthoTop = Number.MIN_VALUE;
  49279. this._orthoBottom = Number.MAX_VALUE;
  49280. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49281. var mesh = renderList[meshIndex];
  49282. if (!mesh) {
  49283. continue;
  49284. }
  49285. var boundingInfo = mesh.getBoundingInfo();
  49286. var boundingBox = boundingInfo.boundingBox;
  49287. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49288. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49289. if (tempVector3.x < this._orthoLeft)
  49290. this._orthoLeft = tempVector3.x;
  49291. if (tempVector3.y < this._orthoBottom)
  49292. this._orthoBottom = tempVector3.y;
  49293. if (tempVector3.x > this._orthoRight)
  49294. this._orthoRight = tempVector3.x;
  49295. if (tempVector3.y > this._orthoTop)
  49296. this._orthoTop = tempVector3.y;
  49297. }
  49298. }
  49299. }
  49300. var xOffset = this._orthoRight - this._orthoLeft;
  49301. var yOffset = this._orthoTop - this._orthoBottom;
  49302. 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);
  49303. };
  49304. DirectionalLight.prototype._buildUniformLayout = function () {
  49305. this._uniformBuffer.addUniform("vLightData", 4);
  49306. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49307. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49308. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49309. this._uniformBuffer.addUniform("depthValues", 2);
  49310. this._uniformBuffer.create();
  49311. };
  49312. /**
  49313. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49314. * @param effect The effect to update
  49315. * @param lightIndex The index of the light in the effect to update
  49316. * @returns The directional light
  49317. */
  49318. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49319. if (this.computeTransformedInformation()) {
  49320. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49321. return this;
  49322. }
  49323. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49324. return this;
  49325. };
  49326. /**
  49327. * Gets the minZ used for shadow according to both the scene and the light.
  49328. *
  49329. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49330. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49331. * @param activeCamera The camera we are returning the min for
  49332. * @returns the depth min z
  49333. */
  49334. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49335. return 1;
  49336. };
  49337. /**
  49338. * Gets the maxZ used for shadow according to both the scene and the light.
  49339. *
  49340. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49341. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49342. * @param activeCamera The camera we are returning the max for
  49343. * @returns the depth max z
  49344. */
  49345. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49346. return 1;
  49347. };
  49348. /**
  49349. * Prepares the list of defines specific to the light type.
  49350. * @param defines the list of defines
  49351. * @param lightIndex defines the index of the light for the effect
  49352. */
  49353. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49354. defines["DIRLIGHT" + lightIndex] = true;
  49355. };
  49356. __decorate([
  49357. BABYLON.serialize()
  49358. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49359. __decorate([
  49360. BABYLON.serialize()
  49361. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49362. __decorate([
  49363. BABYLON.serialize()
  49364. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49365. return DirectionalLight;
  49366. }(BABYLON.ShadowLight));
  49367. BABYLON.DirectionalLight = DirectionalLight;
  49368. })(BABYLON || (BABYLON = {}));
  49369. //# sourceMappingURL=babylon.directionalLight.js.map
  49370. var BABYLON;
  49371. (function (BABYLON) {
  49372. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49373. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49374. });
  49375. /**
  49376. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49377. * These values define a cone of light starting from the position, emitting toward the direction.
  49378. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49379. * and the exponent defines the speed of the decay of the light with distance (reach).
  49380. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49381. */
  49382. var SpotLight = /** @class */ (function (_super) {
  49383. __extends(SpotLight, _super);
  49384. /**
  49385. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49386. * It can cast shadows.
  49387. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49388. * @param name The light friendly name
  49389. * @param position The position of the spot light in the scene
  49390. * @param direction The direction of the light in the scene
  49391. * @param angle The cone angle of the light in Radians
  49392. * @param exponent The light decay speed with the distance from the emission spot
  49393. * @param scene The scene the lights belongs to
  49394. */
  49395. function SpotLight(name, position, direction, angle, exponent, scene) {
  49396. var _this = _super.call(this, name, scene) || this;
  49397. _this._innerAngle = 0;
  49398. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49399. _this._projectionTextureLightNear = 1e-6;
  49400. _this._projectionTextureLightFar = 1000.0;
  49401. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49402. _this._projectionTextureViewLightDirty = true;
  49403. _this._projectionTextureProjectionLightDirty = true;
  49404. _this._projectionTextureDirty = true;
  49405. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49406. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49407. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49408. _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);
  49409. _this.position = position;
  49410. _this.direction = direction;
  49411. _this.angle = angle;
  49412. _this.exponent = exponent;
  49413. return _this;
  49414. }
  49415. Object.defineProperty(SpotLight.prototype, "angle", {
  49416. /**
  49417. * Gets the cone angle of the spot light in Radians.
  49418. */
  49419. get: function () {
  49420. return this._angle;
  49421. },
  49422. /**
  49423. * Sets the cone angle of the spot light in Radians.
  49424. */
  49425. set: function (value) {
  49426. this._angle = value;
  49427. this._cosHalfAngle = Math.cos(value * 0.5);
  49428. this._projectionTextureProjectionLightDirty = true;
  49429. this.forceProjectionMatrixCompute();
  49430. this._computeAngleValues();
  49431. },
  49432. enumerable: true,
  49433. configurable: true
  49434. });
  49435. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49436. /**
  49437. * Only used in gltf falloff mode, this defines the angle where
  49438. * the directional falloff will start before cutting at angle which could be seen
  49439. * as outer angle.
  49440. */
  49441. get: function () {
  49442. return this._angle;
  49443. },
  49444. /**
  49445. * Only used in gltf falloff mode, this defines the angle where
  49446. * the directional falloff will start before cutting at angle which could be seen
  49447. * as outer angle.
  49448. */
  49449. set: function (value) {
  49450. this._innerAngle = value;
  49451. this._computeAngleValues();
  49452. },
  49453. enumerable: true,
  49454. configurable: true
  49455. });
  49456. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49457. /**
  49458. * Allows scaling the angle of the light for shadow generation only.
  49459. */
  49460. get: function () {
  49461. return this._shadowAngleScale;
  49462. },
  49463. /**
  49464. * Allows scaling the angle of the light for shadow generation only.
  49465. */
  49466. set: function (value) {
  49467. this._shadowAngleScale = value;
  49468. this.forceProjectionMatrixCompute();
  49469. },
  49470. enumerable: true,
  49471. configurable: true
  49472. });
  49473. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49474. /**
  49475. * Allows reading the projecton texture
  49476. */
  49477. get: function () {
  49478. return this._projectionTextureMatrix;
  49479. },
  49480. enumerable: true,
  49481. configurable: true
  49482. });
  49483. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49484. /**
  49485. * Gets the near clip of the Spotlight for texture projection.
  49486. */
  49487. get: function () {
  49488. return this._projectionTextureLightNear;
  49489. },
  49490. /**
  49491. * Sets the near clip of the Spotlight for texture projection.
  49492. */
  49493. set: function (value) {
  49494. this._projectionTextureLightNear = value;
  49495. this._projectionTextureProjectionLightDirty = true;
  49496. },
  49497. enumerable: true,
  49498. configurable: true
  49499. });
  49500. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49501. /**
  49502. * Gets the far clip of the Spotlight for texture projection.
  49503. */
  49504. get: function () {
  49505. return this._projectionTextureLightFar;
  49506. },
  49507. /**
  49508. * Sets the far clip of the Spotlight for texture projection.
  49509. */
  49510. set: function (value) {
  49511. this._projectionTextureLightFar = value;
  49512. this._projectionTextureProjectionLightDirty = true;
  49513. },
  49514. enumerable: true,
  49515. configurable: true
  49516. });
  49517. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49518. /**
  49519. * Gets the Up vector of the Spotlight for texture projection.
  49520. */
  49521. get: function () {
  49522. return this._projectionTextureUpDirection;
  49523. },
  49524. /**
  49525. * Sets the Up vector of the Spotlight for texture projection.
  49526. */
  49527. set: function (value) {
  49528. this._projectionTextureUpDirection = value;
  49529. this._projectionTextureProjectionLightDirty = true;
  49530. },
  49531. enumerable: true,
  49532. configurable: true
  49533. });
  49534. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49535. /**
  49536. * Gets the projection texture of the light.
  49537. */
  49538. get: function () {
  49539. return this._projectionTexture;
  49540. },
  49541. /**
  49542. * Sets the projection texture of the light.
  49543. */
  49544. set: function (value) {
  49545. this._projectionTexture = value;
  49546. this._projectionTextureDirty = true;
  49547. },
  49548. enumerable: true,
  49549. configurable: true
  49550. });
  49551. /**
  49552. * Returns the string "SpotLight".
  49553. * @returns the class name
  49554. */
  49555. SpotLight.prototype.getClassName = function () {
  49556. return "SpotLight";
  49557. };
  49558. /**
  49559. * Returns the integer 2.
  49560. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49561. */
  49562. SpotLight.prototype.getTypeID = function () {
  49563. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49564. };
  49565. /**
  49566. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49567. */
  49568. SpotLight.prototype._setDirection = function (value) {
  49569. _super.prototype._setDirection.call(this, value);
  49570. this._projectionTextureViewLightDirty = true;
  49571. };
  49572. /**
  49573. * Overrides the position setter to recompute the projection texture view light Matrix.
  49574. */
  49575. SpotLight.prototype._setPosition = function (value) {
  49576. _super.prototype._setPosition.call(this, value);
  49577. this._projectionTextureViewLightDirty = true;
  49578. };
  49579. /**
  49580. * 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.
  49581. * Returns the SpotLight.
  49582. */
  49583. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49584. var activeCamera = this.getScene().activeCamera;
  49585. if (!activeCamera) {
  49586. return;
  49587. }
  49588. this._shadowAngleScale = this._shadowAngleScale || 1;
  49589. var angle = this._shadowAngleScale * this._angle;
  49590. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49591. };
  49592. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49593. this._projectionTextureViewLightDirty = false;
  49594. this._projectionTextureDirty = true;
  49595. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49596. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49597. };
  49598. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49599. this._projectionTextureProjectionLightDirty = false;
  49600. this._projectionTextureDirty = true;
  49601. var light_far = this.projectionTextureLightFar;
  49602. var light_near = this.projectionTextureLightNear;
  49603. var P = light_far / (light_far - light_near);
  49604. var Q = -P * light_near;
  49605. var S = 1.0 / Math.tan(this._angle / 2.0);
  49606. var A = 1.0;
  49607. 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);
  49608. };
  49609. /**
  49610. * Main function for light texture projection matrix computing.
  49611. */
  49612. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49613. this._projectionTextureDirty = false;
  49614. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49615. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49616. };
  49617. SpotLight.prototype._buildUniformLayout = function () {
  49618. this._uniformBuffer.addUniform("vLightData", 4);
  49619. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49620. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49621. this._uniformBuffer.addUniform("vLightDirection", 3);
  49622. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49623. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49624. this._uniformBuffer.addUniform("depthValues", 2);
  49625. this._uniformBuffer.create();
  49626. };
  49627. SpotLight.prototype._computeAngleValues = function () {
  49628. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49629. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49630. };
  49631. /**
  49632. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49633. * @param effect The effect to update
  49634. * @param lightIndex The index of the light in the effect to update
  49635. * @returns The spot light
  49636. */
  49637. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49638. var normalizeDirection;
  49639. if (this.computeTransformedInformation()) {
  49640. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49641. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49642. }
  49643. else {
  49644. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49645. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49646. }
  49647. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49648. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49649. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49650. if (this._projectionTextureViewLightDirty) {
  49651. this._computeProjectionTextureViewLightMatrix();
  49652. }
  49653. if (this._projectionTextureProjectionLightDirty) {
  49654. this._computeProjectionTextureProjectionLightMatrix();
  49655. }
  49656. if (this._projectionTextureDirty) {
  49657. this._computeProjectionTextureMatrix();
  49658. }
  49659. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49660. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49661. }
  49662. return this;
  49663. };
  49664. /**
  49665. * Disposes the light and the associated resources.
  49666. */
  49667. SpotLight.prototype.dispose = function () {
  49668. _super.prototype.dispose.call(this);
  49669. if (this._projectionTexture) {
  49670. this._projectionTexture.dispose();
  49671. }
  49672. };
  49673. /**
  49674. * Prepares the list of defines specific to the light type.
  49675. * @param defines the list of defines
  49676. * @param lightIndex defines the index of the light for the effect
  49677. */
  49678. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49679. defines["SPOTLIGHT" + lightIndex] = true;
  49680. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49681. };
  49682. __decorate([
  49683. BABYLON.serialize()
  49684. ], SpotLight.prototype, "angle", null);
  49685. __decorate([
  49686. BABYLON.serialize()
  49687. ], SpotLight.prototype, "innerAngle", null);
  49688. __decorate([
  49689. BABYLON.serialize()
  49690. ], SpotLight.prototype, "shadowAngleScale", null);
  49691. __decorate([
  49692. BABYLON.serialize()
  49693. ], SpotLight.prototype, "exponent", void 0);
  49694. __decorate([
  49695. BABYLON.serialize()
  49696. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49697. __decorate([
  49698. BABYLON.serialize()
  49699. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49700. __decorate([
  49701. BABYLON.serialize()
  49702. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49703. __decorate([
  49704. BABYLON.serializeAsTexture("projectedLightTexture")
  49705. ], SpotLight.prototype, "_projectionTexture", void 0);
  49706. return SpotLight;
  49707. }(BABYLON.ShadowLight));
  49708. BABYLON.SpotLight = SpotLight;
  49709. })(BABYLON || (BABYLON = {}));
  49710. //# sourceMappingURL=babylon.spotLight.js.map
  49711. var BABYLON;
  49712. (function (BABYLON) {
  49713. /**
  49714. * Class used to override all child animations of a given target
  49715. */
  49716. var AnimationPropertiesOverride = /** @class */ (function () {
  49717. function AnimationPropertiesOverride() {
  49718. /**
  49719. * Gets or sets a value indicating if animation blending must be used
  49720. */
  49721. this.enableBlending = false;
  49722. /**
  49723. * Gets or sets the blending speed to use when enableBlending is true
  49724. */
  49725. this.blendingSpeed = 0.01;
  49726. /**
  49727. * Gets or sets the default loop mode to use
  49728. */
  49729. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49730. }
  49731. return AnimationPropertiesOverride;
  49732. }());
  49733. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49734. })(BABYLON || (BABYLON = {}));
  49735. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49736. var BABYLON;
  49737. (function (BABYLON) {
  49738. /**
  49739. * Represents the range of an animation
  49740. */
  49741. var AnimationRange = /** @class */ (function () {
  49742. /**
  49743. * Initializes the range of an animation
  49744. * @param name The name of the animation range
  49745. * @param from The starting frame of the animation
  49746. * @param to The ending frame of the animation
  49747. */
  49748. function AnimationRange(
  49749. /**The name of the animation range**/
  49750. name,
  49751. /**The starting frame of the animation */
  49752. from,
  49753. /**The ending frame of the animation*/
  49754. to) {
  49755. this.name = name;
  49756. this.from = from;
  49757. this.to = to;
  49758. }
  49759. /**
  49760. * Makes a copy of the animation range
  49761. * @returns A copy of the animation range
  49762. */
  49763. AnimationRange.prototype.clone = function () {
  49764. return new AnimationRange(this.name, this.from, this.to);
  49765. };
  49766. return AnimationRange;
  49767. }());
  49768. BABYLON.AnimationRange = AnimationRange;
  49769. /**
  49770. * Composed of a frame, and an action function
  49771. */
  49772. var AnimationEvent = /** @class */ (function () {
  49773. /**
  49774. * Initializes the animation event
  49775. * @param frame The frame for which the event is triggered
  49776. * @param action The event to perform when triggered
  49777. * @param onlyOnce Specifies if the event should be triggered only once
  49778. */
  49779. function AnimationEvent(
  49780. /** The frame for which the event is triggered **/
  49781. frame,
  49782. /** The event to perform when triggered **/
  49783. action,
  49784. /** Specifies if the event should be triggered only once**/
  49785. onlyOnce) {
  49786. this.frame = frame;
  49787. this.action = action;
  49788. this.onlyOnce = onlyOnce;
  49789. /**
  49790. * Specifies if the animation event is done
  49791. */
  49792. this.isDone = false;
  49793. }
  49794. /** @hidden */
  49795. AnimationEvent.prototype._clone = function () {
  49796. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49797. };
  49798. return AnimationEvent;
  49799. }());
  49800. BABYLON.AnimationEvent = AnimationEvent;
  49801. /**
  49802. * A cursor which tracks a point on a path
  49803. */
  49804. var PathCursor = /** @class */ (function () {
  49805. /**
  49806. * Initializes the path cursor
  49807. * @param path The path to track
  49808. */
  49809. function PathCursor(path) {
  49810. this.path = path;
  49811. /**
  49812. * Stores path cursor callbacks for when an onchange event is triggered
  49813. */
  49814. this._onchange = new Array();
  49815. /**
  49816. * The value of the path cursor
  49817. */
  49818. this.value = 0;
  49819. /**
  49820. * The animation array of the path cursor
  49821. */
  49822. this.animations = new Array();
  49823. }
  49824. /**
  49825. * Gets the cursor point on the path
  49826. * @returns A point on the path cursor at the cursor location
  49827. */
  49828. PathCursor.prototype.getPoint = function () {
  49829. var point = this.path.getPointAtLengthPosition(this.value);
  49830. return new BABYLON.Vector3(point.x, 0, point.y);
  49831. };
  49832. /**
  49833. * Moves the cursor ahead by the step amount
  49834. * @param step The amount to move the cursor forward
  49835. * @returns This path cursor
  49836. */
  49837. PathCursor.prototype.moveAhead = function (step) {
  49838. if (step === void 0) { step = 0.002; }
  49839. this.move(step);
  49840. return this;
  49841. };
  49842. /**
  49843. * Moves the cursor behind by the step amount
  49844. * @param step The amount to move the cursor back
  49845. * @returns This path cursor
  49846. */
  49847. PathCursor.prototype.moveBack = function (step) {
  49848. if (step === void 0) { step = 0.002; }
  49849. this.move(-step);
  49850. return this;
  49851. };
  49852. /**
  49853. * Moves the cursor by the step amount
  49854. * If the step amount is greater than one, an exception is thrown
  49855. * @param step The amount to move the cursor
  49856. * @returns This path cursor
  49857. */
  49858. PathCursor.prototype.move = function (step) {
  49859. if (Math.abs(step) > 1) {
  49860. throw "step size should be less than 1.";
  49861. }
  49862. this.value += step;
  49863. this.ensureLimits();
  49864. this.raiseOnChange();
  49865. return this;
  49866. };
  49867. /**
  49868. * Ensures that the value is limited between zero and one
  49869. * @returns This path cursor
  49870. */
  49871. PathCursor.prototype.ensureLimits = function () {
  49872. while (this.value > 1) {
  49873. this.value -= 1;
  49874. }
  49875. while (this.value < 0) {
  49876. this.value += 1;
  49877. }
  49878. return this;
  49879. };
  49880. /**
  49881. * Runs onchange callbacks on change (used by the animation engine)
  49882. * @returns This path cursor
  49883. */
  49884. PathCursor.prototype.raiseOnChange = function () {
  49885. var _this = this;
  49886. this._onchange.forEach(function (f) { return f(_this); });
  49887. return this;
  49888. };
  49889. /**
  49890. * Executes a function on change
  49891. * @param f A path cursor onchange callback
  49892. * @returns This path cursor
  49893. */
  49894. PathCursor.prototype.onchange = function (f) {
  49895. this._onchange.push(f);
  49896. return this;
  49897. };
  49898. return PathCursor;
  49899. }());
  49900. BABYLON.PathCursor = PathCursor;
  49901. /**
  49902. * Enum for the animation key frame interpolation type
  49903. */
  49904. var AnimationKeyInterpolation;
  49905. (function (AnimationKeyInterpolation) {
  49906. /**
  49907. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49908. */
  49909. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49910. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49911. /**
  49912. * Class used to store any kind of animation
  49913. */
  49914. var Animation = /** @class */ (function () {
  49915. /**
  49916. * Initializes the animation
  49917. * @param name Name of the animation
  49918. * @param targetProperty Property to animate
  49919. * @param framePerSecond The frames per second of the animation
  49920. * @param dataType The data type of the animation
  49921. * @param loopMode The loop mode of the animation
  49922. * @param enableBlendings Specifies if blending should be enabled
  49923. */
  49924. function Animation(
  49925. /**Name of the animation */
  49926. name,
  49927. /**Property to animate */
  49928. targetProperty,
  49929. /**The frames per second of the animation */
  49930. framePerSecond,
  49931. /**The data type of the animation */
  49932. dataType,
  49933. /**The loop mode of the animation */
  49934. loopMode,
  49935. /**Specifies if blending should be enabled */
  49936. enableBlending) {
  49937. this.name = name;
  49938. this.targetProperty = targetProperty;
  49939. this.framePerSecond = framePerSecond;
  49940. this.dataType = dataType;
  49941. this.loopMode = loopMode;
  49942. this.enableBlending = enableBlending;
  49943. /**
  49944. * @hidden Internal use only
  49945. */
  49946. this._runtimeAnimations = new Array();
  49947. /**
  49948. * The set of event that will be linked to this animation
  49949. */
  49950. this._events = new Array();
  49951. /**
  49952. * Stores the blending speed of the animation
  49953. */
  49954. this.blendingSpeed = 0.01;
  49955. /**
  49956. * Stores the animation ranges for the animation
  49957. */
  49958. this._ranges = {};
  49959. this.targetPropertyPath = targetProperty.split(".");
  49960. this.dataType = dataType;
  49961. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49962. }
  49963. /**
  49964. * @hidden Internal use
  49965. */
  49966. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49967. var dataType = undefined;
  49968. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49969. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49970. }
  49971. else if (from instanceof BABYLON.Quaternion) {
  49972. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49973. }
  49974. else if (from instanceof BABYLON.Vector3) {
  49975. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49976. }
  49977. else if (from instanceof BABYLON.Vector2) {
  49978. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49979. }
  49980. else if (from instanceof BABYLON.Color3) {
  49981. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49982. }
  49983. else if (from instanceof BABYLON.Size) {
  49984. dataType = Animation.ANIMATIONTYPE_SIZE;
  49985. }
  49986. if (dataType == undefined) {
  49987. return null;
  49988. }
  49989. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49990. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49991. animation.setKeys(keys);
  49992. if (easingFunction !== undefined) {
  49993. animation.setEasingFunction(easingFunction);
  49994. }
  49995. return animation;
  49996. };
  49997. /**
  49998. * Sets up an animation
  49999. * @param property The property to animate
  50000. * @param animationType The animation type to apply
  50001. * @param framePerSecond The frames per second of the animation
  50002. * @param easingFunction The easing function used in the animation
  50003. * @returns The created animation
  50004. */
  50005. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50006. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50007. animation.setEasingFunction(easingFunction);
  50008. return animation;
  50009. };
  50010. /**
  50011. * Create and start an animation on a node
  50012. * @param name defines the name of the global animation that will be run on all nodes
  50013. * @param node defines the root node where the animation will take place
  50014. * @param targetProperty defines property to animate
  50015. * @param framePerSecond defines the number of frame per second yo use
  50016. * @param totalFrame defines the number of frames in total
  50017. * @param from defines the initial value
  50018. * @param to defines the final value
  50019. * @param loopMode defines which loop mode you want to use (off by default)
  50020. * @param easingFunction defines the easing function to use (linear by default)
  50021. * @param onAnimationEnd defines the callback to call when animation end
  50022. * @returns the animatable created for this animation
  50023. */
  50024. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50025. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50026. if (!animation) {
  50027. return null;
  50028. }
  50029. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50030. };
  50031. /**
  50032. * Create and start an animation on a node and its descendants
  50033. * @param name defines the name of the global animation that will be run on all nodes
  50034. * @param node defines the root node where the animation will take place
  50035. * @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
  50036. * @param targetProperty defines property to animate
  50037. * @param framePerSecond defines the number of frame per second to use
  50038. * @param totalFrame defines the number of frames in total
  50039. * @param from defines the initial value
  50040. * @param to defines the final value
  50041. * @param loopMode defines which loop mode you want to use (off by default)
  50042. * @param easingFunction defines the easing function to use (linear by default)
  50043. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50044. * @returns the list of animatables created for all nodes
  50045. * @example https://www.babylonjs-playground.com/#MH0VLI
  50046. */
  50047. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50048. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50049. if (!animation) {
  50050. return null;
  50051. }
  50052. var scene = node.getScene();
  50053. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50054. };
  50055. /**
  50056. * Creates a new animation, merges it with the existing animations and starts it
  50057. * @param name Name of the animation
  50058. * @param node Node which contains the scene that begins the animations
  50059. * @param targetProperty Specifies which property to animate
  50060. * @param framePerSecond The frames per second of the animation
  50061. * @param totalFrame The total number of frames
  50062. * @param from The frame at the beginning of the animation
  50063. * @param to The frame at the end of the animation
  50064. * @param loopMode Specifies the loop mode of the animation
  50065. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50066. * @param onAnimationEnd Callback to run once the animation is complete
  50067. * @returns Nullable animation
  50068. */
  50069. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50070. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50071. if (!animation) {
  50072. return null;
  50073. }
  50074. node.animations.push(animation);
  50075. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50076. };
  50077. /**
  50078. * Transition property of an host to the target Value
  50079. * @param property The property to transition
  50080. * @param targetValue The target Value of the property
  50081. * @param host The object where the property to animate belongs
  50082. * @param scene Scene used to run the animation
  50083. * @param frameRate Framerate (in frame/s) to use
  50084. * @param transition The transition type we want to use
  50085. * @param duration The duration of the animation, in milliseconds
  50086. * @param onAnimationEnd Callback trigger at the end of the animation
  50087. * @returns Nullable animation
  50088. */
  50089. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50090. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50091. if (duration <= 0) {
  50092. host[property] = targetValue;
  50093. if (onAnimationEnd) {
  50094. onAnimationEnd();
  50095. }
  50096. return null;
  50097. }
  50098. var endFrame = frameRate * (duration / 1000);
  50099. transition.setKeys([{
  50100. frame: 0,
  50101. value: host[property].clone ? host[property].clone() : host[property]
  50102. },
  50103. {
  50104. frame: endFrame,
  50105. value: targetValue
  50106. }]);
  50107. if (!host.animations) {
  50108. host.animations = [];
  50109. }
  50110. host.animations.push(transition);
  50111. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50112. animation.onAnimationEnd = onAnimationEnd;
  50113. return animation;
  50114. };
  50115. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50116. /**
  50117. * Return the array of runtime animations currently using this animation
  50118. */
  50119. get: function () {
  50120. return this._runtimeAnimations;
  50121. },
  50122. enumerable: true,
  50123. configurable: true
  50124. });
  50125. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50126. /**
  50127. * Specifies if any of the runtime animations are currently running
  50128. */
  50129. get: function () {
  50130. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50131. var runtimeAnimation = _a[_i];
  50132. if (!runtimeAnimation.isStopped) {
  50133. return true;
  50134. }
  50135. }
  50136. return false;
  50137. },
  50138. enumerable: true,
  50139. configurable: true
  50140. });
  50141. // Methods
  50142. /**
  50143. * Converts the animation to a string
  50144. * @param fullDetails support for multiple levels of logging within scene loading
  50145. * @returns String form of the animation
  50146. */
  50147. Animation.prototype.toString = function (fullDetails) {
  50148. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50149. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50150. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50151. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50152. if (fullDetails) {
  50153. ret += ", Ranges: {";
  50154. var first = true;
  50155. for (var name in this._ranges) {
  50156. if (first) {
  50157. ret += ", ";
  50158. first = false;
  50159. }
  50160. ret += name;
  50161. }
  50162. ret += "}";
  50163. }
  50164. return ret;
  50165. };
  50166. /**
  50167. * Add an event to this animation
  50168. * @param event Event to add
  50169. */
  50170. Animation.prototype.addEvent = function (event) {
  50171. this._events.push(event);
  50172. };
  50173. /**
  50174. * Remove all events found at the given frame
  50175. * @param frame The frame to remove events from
  50176. */
  50177. Animation.prototype.removeEvents = function (frame) {
  50178. for (var index = 0; index < this._events.length; index++) {
  50179. if (this._events[index].frame === frame) {
  50180. this._events.splice(index, 1);
  50181. index--;
  50182. }
  50183. }
  50184. };
  50185. /**
  50186. * Retrieves all the events from the animation
  50187. * @returns Events from the animation
  50188. */
  50189. Animation.prototype.getEvents = function () {
  50190. return this._events;
  50191. };
  50192. /**
  50193. * Creates an animation range
  50194. * @param name Name of the animation range
  50195. * @param from Starting frame of the animation range
  50196. * @param to Ending frame of the animation
  50197. */
  50198. Animation.prototype.createRange = function (name, from, to) {
  50199. // check name not already in use; could happen for bones after serialized
  50200. if (!this._ranges[name]) {
  50201. this._ranges[name] = new AnimationRange(name, from, to);
  50202. }
  50203. };
  50204. /**
  50205. * Deletes an animation range by name
  50206. * @param name Name of the animation range to delete
  50207. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50208. */
  50209. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50210. if (deleteFrames === void 0) { deleteFrames = true; }
  50211. var range = this._ranges[name];
  50212. if (!range) {
  50213. return;
  50214. }
  50215. if (deleteFrames) {
  50216. var from = range.from;
  50217. var to = range.to;
  50218. // this loop MUST go high to low for multiple splices to work
  50219. for (var key = this._keys.length - 1; key >= 0; key--) {
  50220. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50221. this._keys.splice(key, 1);
  50222. }
  50223. }
  50224. }
  50225. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50226. };
  50227. /**
  50228. * Gets the animation range by name, or null if not defined
  50229. * @param name Name of the animation range
  50230. * @returns Nullable animation range
  50231. */
  50232. Animation.prototype.getRange = function (name) {
  50233. return this._ranges[name];
  50234. };
  50235. /**
  50236. * Gets the key frames from the animation
  50237. * @returns The key frames of the animation
  50238. */
  50239. Animation.prototype.getKeys = function () {
  50240. return this._keys;
  50241. };
  50242. /**
  50243. * Gets the highest frame rate of the animation
  50244. * @returns Highest frame rate of the animation
  50245. */
  50246. Animation.prototype.getHighestFrame = function () {
  50247. var ret = 0;
  50248. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50249. if (ret < this._keys[key].frame) {
  50250. ret = this._keys[key].frame;
  50251. }
  50252. }
  50253. return ret;
  50254. };
  50255. /**
  50256. * Gets the easing function of the animation
  50257. * @returns Easing function of the animation
  50258. */
  50259. Animation.prototype.getEasingFunction = function () {
  50260. return this._easingFunction;
  50261. };
  50262. /**
  50263. * Sets the easing function of the animation
  50264. * @param easingFunction A custom mathematical formula for animation
  50265. */
  50266. Animation.prototype.setEasingFunction = function (easingFunction) {
  50267. this._easingFunction = easingFunction;
  50268. };
  50269. /**
  50270. * Interpolates a scalar linearly
  50271. * @param startValue Start value of the animation curve
  50272. * @param endValue End value of the animation curve
  50273. * @param gradient Scalar amount to interpolate
  50274. * @returns Interpolated scalar value
  50275. */
  50276. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50277. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50278. };
  50279. /**
  50280. * Interpolates a scalar cubically
  50281. * @param startValue Start value of the animation curve
  50282. * @param outTangent End tangent of the animation
  50283. * @param endValue End value of the animation curve
  50284. * @param inTangent Start tangent of the animation curve
  50285. * @param gradient Scalar amount to interpolate
  50286. * @returns Interpolated scalar value
  50287. */
  50288. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50289. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50290. };
  50291. /**
  50292. * Interpolates a quaternion using a spherical linear interpolation
  50293. * @param startValue Start value of the animation curve
  50294. * @param endValue End value of the animation curve
  50295. * @param gradient Scalar amount to interpolate
  50296. * @returns Interpolated quaternion value
  50297. */
  50298. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50299. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50300. };
  50301. /**
  50302. * Interpolates a quaternion cubically
  50303. * @param startValue Start value of the animation curve
  50304. * @param outTangent End tangent of the animation curve
  50305. * @param endValue End value of the animation curve
  50306. * @param inTangent Start tangent of the animation curve
  50307. * @param gradient Scalar amount to interpolate
  50308. * @returns Interpolated quaternion value
  50309. */
  50310. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50311. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50312. };
  50313. /**
  50314. * Interpolates a Vector3 linearl
  50315. * @param startValue Start value of the animation curve
  50316. * @param endValue End value of the animation curve
  50317. * @param gradient Scalar amount to interpolate
  50318. * @returns Interpolated scalar value
  50319. */
  50320. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50321. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50322. };
  50323. /**
  50324. * Interpolates a Vector3 cubically
  50325. * @param startValue Start value of the animation curve
  50326. * @param outTangent End tangent of the animation
  50327. * @param endValue End value of the animation curve
  50328. * @param inTangent Start tangent of the animation curve
  50329. * @param gradient Scalar amount to interpolate
  50330. * @returns InterpolatedVector3 value
  50331. */
  50332. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50333. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50334. };
  50335. /**
  50336. * Interpolates a Vector2 linearly
  50337. * @param startValue Start value of the animation curve
  50338. * @param endValue End value of the animation curve
  50339. * @param gradient Scalar amount to interpolate
  50340. * @returns Interpolated Vector2 value
  50341. */
  50342. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50343. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50344. };
  50345. /**
  50346. * Interpolates a Vector2 cubically
  50347. * @param startValue Start value of the animation curve
  50348. * @param outTangent End tangent of the animation
  50349. * @param endValue End value of the animation curve
  50350. * @param inTangent Start tangent of the animation curve
  50351. * @param gradient Scalar amount to interpolate
  50352. * @returns Interpolated Vector2 value
  50353. */
  50354. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50355. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50356. };
  50357. /**
  50358. * Interpolates a size linearly
  50359. * @param startValue Start value of the animation curve
  50360. * @param endValue End value of the animation curve
  50361. * @param gradient Scalar amount to interpolate
  50362. * @returns Interpolated Size value
  50363. */
  50364. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50365. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50366. };
  50367. /**
  50368. * Interpolates a Color3 linearly
  50369. * @param startValue Start value of the animation curve
  50370. * @param endValue End value of the animation curve
  50371. * @param gradient Scalar amount to interpolate
  50372. * @returns Interpolated Color3 value
  50373. */
  50374. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50375. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50376. };
  50377. /**
  50378. * @hidden Internal use only
  50379. */
  50380. Animation.prototype._getKeyValue = function (value) {
  50381. if (typeof value === "function") {
  50382. return value();
  50383. }
  50384. return value;
  50385. };
  50386. /**
  50387. * @hidden Internal use only
  50388. */
  50389. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50390. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50391. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50392. }
  50393. var keys = this.getKeys();
  50394. // Try to get a hash to find the right key
  50395. 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));
  50396. if (keys[startKeyIndex].frame >= currentFrame) {
  50397. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50398. startKeyIndex--;
  50399. }
  50400. }
  50401. for (var key = startKeyIndex; key < keys.length; key++) {
  50402. var endKey = keys[key + 1];
  50403. if (endKey.frame >= currentFrame) {
  50404. var startKey = keys[key];
  50405. var startValue = this._getKeyValue(startKey.value);
  50406. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50407. return startValue;
  50408. }
  50409. var endValue = this._getKeyValue(endKey.value);
  50410. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50411. var frameDelta = endKey.frame - startKey.frame;
  50412. // gradient : percent of currentFrame between the frame inf and the frame sup
  50413. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50414. // check for easingFunction and correction of gradient
  50415. var easingFunction = this.getEasingFunction();
  50416. if (easingFunction != null) {
  50417. gradient = easingFunction.ease(gradient);
  50418. }
  50419. switch (this.dataType) {
  50420. // Float
  50421. case Animation.ANIMATIONTYPE_FLOAT:
  50422. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50423. switch (loopMode) {
  50424. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50425. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50426. return floatValue;
  50427. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50428. return offsetValue * repeatCount + floatValue;
  50429. }
  50430. break;
  50431. // Quaternion
  50432. case Animation.ANIMATIONTYPE_QUATERNION:
  50433. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50434. switch (loopMode) {
  50435. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50436. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50437. return quatValue;
  50438. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50439. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50440. }
  50441. return quatValue;
  50442. // Vector3
  50443. case Animation.ANIMATIONTYPE_VECTOR3:
  50444. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50445. switch (loopMode) {
  50446. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50447. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50448. return vec3Value;
  50449. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50450. return vec3Value.add(offsetValue.scale(repeatCount));
  50451. }
  50452. // Vector2
  50453. case Animation.ANIMATIONTYPE_VECTOR2:
  50454. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50455. switch (loopMode) {
  50456. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50457. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50458. return vec2Value;
  50459. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50460. return vec2Value.add(offsetValue.scale(repeatCount));
  50461. }
  50462. // Size
  50463. case Animation.ANIMATIONTYPE_SIZE:
  50464. switch (loopMode) {
  50465. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50466. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50467. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50468. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50469. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50470. }
  50471. // Color3
  50472. case Animation.ANIMATIONTYPE_COLOR3:
  50473. switch (loopMode) {
  50474. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50475. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50476. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50477. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50478. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50479. }
  50480. // Matrix
  50481. case Animation.ANIMATIONTYPE_MATRIX:
  50482. switch (loopMode) {
  50483. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50484. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50485. if (Animation.AllowMatricesInterpolation) {
  50486. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50487. }
  50488. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50489. return startValue;
  50490. }
  50491. default:
  50492. break;
  50493. }
  50494. break;
  50495. }
  50496. }
  50497. return this._getKeyValue(keys[keys.length - 1].value);
  50498. };
  50499. /**
  50500. * Defines the function to use to interpolate matrices
  50501. * @param startValue defines the start matrix
  50502. * @param endValue defines the end matrix
  50503. * @param gradient defines the gradient between both matrices
  50504. * @param result defines an optional target matrix where to store the interpolation
  50505. * @returns the interpolated matrix
  50506. */
  50507. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50508. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50509. if (result) {
  50510. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50511. return result;
  50512. }
  50513. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50514. }
  50515. if (result) {
  50516. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50517. return result;
  50518. }
  50519. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50520. };
  50521. /**
  50522. * Makes a copy of the animation
  50523. * @returns Cloned animation
  50524. */
  50525. Animation.prototype.clone = function () {
  50526. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50527. clone.enableBlending = this.enableBlending;
  50528. clone.blendingSpeed = this.blendingSpeed;
  50529. if (this._keys) {
  50530. clone.setKeys(this._keys);
  50531. }
  50532. if (this._ranges) {
  50533. clone._ranges = {};
  50534. for (var name in this._ranges) {
  50535. var range = this._ranges[name];
  50536. if (!range) {
  50537. continue;
  50538. }
  50539. clone._ranges[name] = range.clone();
  50540. }
  50541. }
  50542. return clone;
  50543. };
  50544. /**
  50545. * Sets the key frames of the animation
  50546. * @param values The animation key frames to set
  50547. */
  50548. Animation.prototype.setKeys = function (values) {
  50549. this._keys = values.slice(0);
  50550. };
  50551. /**
  50552. * Serializes the animation to an object
  50553. * @returns Serialized object
  50554. */
  50555. Animation.prototype.serialize = function () {
  50556. var serializationObject = {};
  50557. serializationObject.name = this.name;
  50558. serializationObject.property = this.targetProperty;
  50559. serializationObject.framePerSecond = this.framePerSecond;
  50560. serializationObject.dataType = this.dataType;
  50561. serializationObject.loopBehavior = this.loopMode;
  50562. serializationObject.enableBlending = this.enableBlending;
  50563. serializationObject.blendingSpeed = this.blendingSpeed;
  50564. var dataType = this.dataType;
  50565. serializationObject.keys = [];
  50566. var keys = this.getKeys();
  50567. for (var index = 0; index < keys.length; index++) {
  50568. var animationKey = keys[index];
  50569. var key = {};
  50570. key.frame = animationKey.frame;
  50571. switch (dataType) {
  50572. case Animation.ANIMATIONTYPE_FLOAT:
  50573. key.values = [animationKey.value];
  50574. break;
  50575. case Animation.ANIMATIONTYPE_QUATERNION:
  50576. case Animation.ANIMATIONTYPE_MATRIX:
  50577. case Animation.ANIMATIONTYPE_VECTOR3:
  50578. case Animation.ANIMATIONTYPE_COLOR3:
  50579. key.values = animationKey.value.asArray();
  50580. break;
  50581. }
  50582. serializationObject.keys.push(key);
  50583. }
  50584. serializationObject.ranges = [];
  50585. for (var name in this._ranges) {
  50586. var source = this._ranges[name];
  50587. if (!source) {
  50588. continue;
  50589. }
  50590. var range = {};
  50591. range.name = name;
  50592. range.from = source.from;
  50593. range.to = source.to;
  50594. serializationObject.ranges.push(range);
  50595. }
  50596. return serializationObject;
  50597. };
  50598. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50599. /**
  50600. * Get the float animation type
  50601. */
  50602. get: function () {
  50603. return Animation._ANIMATIONTYPE_FLOAT;
  50604. },
  50605. enumerable: true,
  50606. configurable: true
  50607. });
  50608. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50609. /**
  50610. * Get the Vector3 animation type
  50611. */
  50612. get: function () {
  50613. return Animation._ANIMATIONTYPE_VECTOR3;
  50614. },
  50615. enumerable: true,
  50616. configurable: true
  50617. });
  50618. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50619. /**
  50620. * Get the Vector2 animation type
  50621. */
  50622. get: function () {
  50623. return Animation._ANIMATIONTYPE_VECTOR2;
  50624. },
  50625. enumerable: true,
  50626. configurable: true
  50627. });
  50628. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50629. /**
  50630. * Get the Size animation type
  50631. */
  50632. get: function () {
  50633. return Animation._ANIMATIONTYPE_SIZE;
  50634. },
  50635. enumerable: true,
  50636. configurable: true
  50637. });
  50638. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50639. /**
  50640. * Get the Quaternion animation type
  50641. */
  50642. get: function () {
  50643. return Animation._ANIMATIONTYPE_QUATERNION;
  50644. },
  50645. enumerable: true,
  50646. configurable: true
  50647. });
  50648. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50649. /**
  50650. * Get the Matrix animation type
  50651. */
  50652. get: function () {
  50653. return Animation._ANIMATIONTYPE_MATRIX;
  50654. },
  50655. enumerable: true,
  50656. configurable: true
  50657. });
  50658. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50659. /**
  50660. * Get the Color3 animation type
  50661. */
  50662. get: function () {
  50663. return Animation._ANIMATIONTYPE_COLOR3;
  50664. },
  50665. enumerable: true,
  50666. configurable: true
  50667. });
  50668. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50669. /**
  50670. * Get the Relative Loop Mode
  50671. */
  50672. get: function () {
  50673. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50679. /**
  50680. * Get the Cycle Loop Mode
  50681. */
  50682. get: function () {
  50683. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50689. /**
  50690. * Get the Constant Loop Mode
  50691. */
  50692. get: function () {
  50693. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50694. },
  50695. enumerable: true,
  50696. configurable: true
  50697. });
  50698. /** @hidden */
  50699. Animation._UniversalLerp = function (left, right, amount) {
  50700. var constructor = left.constructor;
  50701. if (constructor.Lerp) { // Lerp supported
  50702. return constructor.Lerp(left, right, amount);
  50703. }
  50704. else if (constructor.Slerp) { // Slerp supported
  50705. return constructor.Slerp(left, right, amount);
  50706. }
  50707. else if (left.toFixed) { // Number
  50708. return left * (1.0 - amount) + amount * right;
  50709. }
  50710. else { // Blending not supported
  50711. return right;
  50712. }
  50713. };
  50714. /**
  50715. * Parses an animation object and creates an animation
  50716. * @param parsedAnimation Parsed animation object
  50717. * @returns Animation object
  50718. */
  50719. Animation.Parse = function (parsedAnimation) {
  50720. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50721. var dataType = parsedAnimation.dataType;
  50722. var keys = [];
  50723. var data;
  50724. var index;
  50725. if (parsedAnimation.enableBlending) {
  50726. animation.enableBlending = parsedAnimation.enableBlending;
  50727. }
  50728. if (parsedAnimation.blendingSpeed) {
  50729. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50730. }
  50731. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50732. var key = parsedAnimation.keys[index];
  50733. var inTangent;
  50734. var outTangent;
  50735. switch (dataType) {
  50736. case Animation.ANIMATIONTYPE_FLOAT:
  50737. data = key.values[0];
  50738. if (key.values.length >= 1) {
  50739. inTangent = key.values[1];
  50740. }
  50741. if (key.values.length >= 2) {
  50742. outTangent = key.values[2];
  50743. }
  50744. break;
  50745. case Animation.ANIMATIONTYPE_QUATERNION:
  50746. data = BABYLON.Quaternion.FromArray(key.values);
  50747. if (key.values.length >= 8) {
  50748. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50749. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50750. inTangent = _inTangent;
  50751. }
  50752. }
  50753. if (key.values.length >= 12) {
  50754. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50755. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50756. outTangent = _outTangent;
  50757. }
  50758. }
  50759. break;
  50760. case Animation.ANIMATIONTYPE_MATRIX:
  50761. data = BABYLON.Matrix.FromArray(key.values);
  50762. break;
  50763. case Animation.ANIMATIONTYPE_COLOR3:
  50764. data = BABYLON.Color3.FromArray(key.values);
  50765. break;
  50766. case Animation.ANIMATIONTYPE_VECTOR3:
  50767. default:
  50768. data = BABYLON.Vector3.FromArray(key.values);
  50769. break;
  50770. }
  50771. var keyData = {};
  50772. keyData.frame = key.frame;
  50773. keyData.value = data;
  50774. if (inTangent != undefined) {
  50775. keyData.inTangent = inTangent;
  50776. }
  50777. if (outTangent != undefined) {
  50778. keyData.outTangent = outTangent;
  50779. }
  50780. keys.push(keyData);
  50781. }
  50782. animation.setKeys(keys);
  50783. if (parsedAnimation.ranges) {
  50784. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50785. data = parsedAnimation.ranges[index];
  50786. animation.createRange(data.name, data.from, data.to);
  50787. }
  50788. }
  50789. return animation;
  50790. };
  50791. /**
  50792. * Appends the serialized animations from the source animations
  50793. * @param source Source containing the animations
  50794. * @param destination Target to store the animations
  50795. */
  50796. Animation.AppendSerializedAnimations = function (source, destination) {
  50797. if (source.animations) {
  50798. destination.animations = [];
  50799. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50800. var animation = source.animations[animationIndex];
  50801. destination.animations.push(animation.serialize());
  50802. }
  50803. }
  50804. };
  50805. /**
  50806. * Use matrix interpolation instead of using direct key value when animating matrices
  50807. */
  50808. Animation.AllowMatricesInterpolation = false;
  50809. /**
  50810. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50811. */
  50812. Animation.AllowMatrixDecomposeForInterpolation = true;
  50813. // Statics
  50814. /**
  50815. * Float animation type
  50816. */
  50817. Animation._ANIMATIONTYPE_FLOAT = 0;
  50818. /**
  50819. * Vector3 animation type
  50820. */
  50821. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50822. /**
  50823. * Quaternion animation type
  50824. */
  50825. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50826. /**
  50827. * Matrix animation type
  50828. */
  50829. Animation._ANIMATIONTYPE_MATRIX = 3;
  50830. /**
  50831. * Color3 animation type
  50832. */
  50833. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50834. /**
  50835. * Vector2 animation type
  50836. */
  50837. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50838. /**
  50839. * Size animation type
  50840. */
  50841. Animation._ANIMATIONTYPE_SIZE = 6;
  50842. /**
  50843. * Relative Loop Mode
  50844. */
  50845. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50846. /**
  50847. * Cycle Loop Mode
  50848. */
  50849. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50850. /**
  50851. * Constant Loop Mode
  50852. */
  50853. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50854. return Animation;
  50855. }());
  50856. BABYLON.Animation = Animation;
  50857. })(BABYLON || (BABYLON = {}));
  50858. //# sourceMappingURL=babylon.animation.js.map
  50859. var BABYLON;
  50860. (function (BABYLON) {
  50861. /**
  50862. * This class defines the direct association between an animation and a target
  50863. */
  50864. var TargetedAnimation = /** @class */ (function () {
  50865. function TargetedAnimation() {
  50866. }
  50867. return TargetedAnimation;
  50868. }());
  50869. BABYLON.TargetedAnimation = TargetedAnimation;
  50870. /**
  50871. * Use this class to create coordinated animations on multiple targets
  50872. */
  50873. var AnimationGroup = /** @class */ (function () {
  50874. function AnimationGroup(name, scene) {
  50875. if (scene === void 0) { scene = null; }
  50876. this.name = name;
  50877. this._targetedAnimations = new Array();
  50878. this._animatables = new Array();
  50879. this._from = Number.MAX_VALUE;
  50880. this._to = -Number.MAX_VALUE;
  50881. this._speedRatio = 1;
  50882. this.onAnimationEndObservable = new BABYLON.Observable();
  50883. /**
  50884. * This observable will notify when all animations have ended.
  50885. */
  50886. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50887. /**
  50888. * This observable will notify when all animations have paused.
  50889. */
  50890. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50891. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50892. this._scene.animationGroups.push(this);
  50893. }
  50894. Object.defineProperty(AnimationGroup.prototype, "from", {
  50895. /**
  50896. * Gets the first frame
  50897. */
  50898. get: function () {
  50899. return this._from;
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. Object.defineProperty(AnimationGroup.prototype, "to", {
  50905. /**
  50906. * Gets the last frame
  50907. */
  50908. get: function () {
  50909. return this._to;
  50910. },
  50911. enumerable: true,
  50912. configurable: true
  50913. });
  50914. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50915. /**
  50916. * Define if the animations are started
  50917. */
  50918. get: function () {
  50919. return this._isStarted;
  50920. },
  50921. enumerable: true,
  50922. configurable: true
  50923. });
  50924. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50925. /**
  50926. * Gets or sets the speed ratio to use for all animations
  50927. */
  50928. get: function () {
  50929. return this._speedRatio;
  50930. },
  50931. /**
  50932. * Gets or sets the speed ratio to use for all animations
  50933. */
  50934. set: function (value) {
  50935. if (this._speedRatio === value) {
  50936. return;
  50937. }
  50938. this._speedRatio = value;
  50939. for (var index = 0; index < this._animatables.length; index++) {
  50940. var animatable = this._animatables[index];
  50941. animatable.speedRatio = this._speedRatio;
  50942. }
  50943. },
  50944. enumerable: true,
  50945. configurable: true
  50946. });
  50947. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50948. /**
  50949. * Gets the targeted animations for this animation group
  50950. */
  50951. get: function () {
  50952. return this._targetedAnimations;
  50953. },
  50954. enumerable: true,
  50955. configurable: true
  50956. });
  50957. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50958. /**
  50959. * returning the list of animatables controlled by this animation group.
  50960. */
  50961. get: function () {
  50962. return this._animatables;
  50963. },
  50964. enumerable: true,
  50965. configurable: true
  50966. });
  50967. /**
  50968. * Add an animation (with its target) in the group
  50969. * @param animation defines the animation we want to add
  50970. * @param target defines the target of the animation
  50971. * @returns the {BABYLON.TargetedAnimation} object
  50972. */
  50973. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50974. var targetedAnimation = {
  50975. animation: animation,
  50976. target: target
  50977. };
  50978. var keys = animation.getKeys();
  50979. if (this._from > keys[0].frame) {
  50980. this._from = keys[0].frame;
  50981. }
  50982. if (this._to < keys[keys.length - 1].frame) {
  50983. this._to = keys[keys.length - 1].frame;
  50984. }
  50985. this._targetedAnimations.push(targetedAnimation);
  50986. return targetedAnimation;
  50987. };
  50988. /**
  50989. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50990. * It can add constant keys at begin or end
  50991. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50992. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50993. */
  50994. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50995. if (beginFrame === void 0) { beginFrame = null; }
  50996. if (endFrame === void 0) { endFrame = null; }
  50997. if (beginFrame == null)
  50998. beginFrame = this._from;
  50999. if (endFrame == null)
  51000. endFrame = this._to;
  51001. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51002. var targetedAnimation = this._targetedAnimations[index];
  51003. var keys = targetedAnimation.animation.getKeys();
  51004. var startKey = keys[0];
  51005. var endKey = keys[keys.length - 1];
  51006. if (startKey.frame > beginFrame) {
  51007. var newKey = {
  51008. frame: beginFrame,
  51009. value: startKey.value,
  51010. inTangent: startKey.inTangent,
  51011. outTangent: startKey.outTangent,
  51012. interpolation: startKey.interpolation
  51013. };
  51014. keys.splice(0, 0, newKey);
  51015. }
  51016. if (endKey.frame < endFrame) {
  51017. var newKey = {
  51018. frame: endFrame,
  51019. value: endKey.value,
  51020. inTangent: endKey.outTangent,
  51021. outTangent: endKey.outTangent,
  51022. interpolation: endKey.interpolation
  51023. };
  51024. keys.push(newKey);
  51025. }
  51026. }
  51027. this._from = beginFrame;
  51028. this._to = endFrame;
  51029. return this;
  51030. };
  51031. /**
  51032. * Start all animations on given targets
  51033. * @param loop defines if animations must loop
  51034. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51035. * @param from defines the from key (optional)
  51036. * @param to defines the to key (optional)
  51037. * @returns the current animation group
  51038. */
  51039. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51040. var _this = this;
  51041. if (loop === void 0) { loop = false; }
  51042. if (speedRatio === void 0) { speedRatio = 1; }
  51043. if (this._isStarted || this._targetedAnimations.length === 0) {
  51044. return this;
  51045. }
  51046. var _loop_1 = function (targetedAnimation) {
  51047. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51048. animatable.onAnimationEnd = function () {
  51049. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51050. _this._checkAnimationGroupEnded(animatable);
  51051. };
  51052. this_1._animatables.push(animatable);
  51053. };
  51054. var this_1 = this;
  51055. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51056. var targetedAnimation = _a[_i];
  51057. _loop_1(targetedAnimation);
  51058. }
  51059. this._speedRatio = speedRatio;
  51060. this._isStarted = true;
  51061. return this;
  51062. };
  51063. /**
  51064. * Pause all animations
  51065. */
  51066. AnimationGroup.prototype.pause = function () {
  51067. if (!this._isStarted) {
  51068. return this;
  51069. }
  51070. for (var index = 0; index < this._animatables.length; index++) {
  51071. var animatable = this._animatables[index];
  51072. animatable.pause();
  51073. }
  51074. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51075. return this;
  51076. };
  51077. /**
  51078. * Play all animations to initial state
  51079. * This function will start() the animations if they were not started or will restart() them if they were paused
  51080. * @param loop defines if animations must loop
  51081. */
  51082. AnimationGroup.prototype.play = function (loop) {
  51083. // only if all animatables are ready and exist
  51084. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51085. if (loop !== undefined) {
  51086. for (var index = 0; index < this._animatables.length; index++) {
  51087. var animatable = this._animatables[index];
  51088. animatable.loopAnimation = loop;
  51089. }
  51090. }
  51091. this.restart();
  51092. }
  51093. else {
  51094. this.stop();
  51095. this.start(loop, this._speedRatio);
  51096. }
  51097. return this;
  51098. };
  51099. /**
  51100. * Reset all animations to initial state
  51101. */
  51102. AnimationGroup.prototype.reset = function () {
  51103. if (!this._isStarted) {
  51104. return this;
  51105. }
  51106. for (var index = 0; index < this._animatables.length; index++) {
  51107. var animatable = this._animatables[index];
  51108. animatable.reset();
  51109. }
  51110. return this;
  51111. };
  51112. /**
  51113. * Restart animations from key 0
  51114. */
  51115. AnimationGroup.prototype.restart = function () {
  51116. if (!this._isStarted) {
  51117. return this;
  51118. }
  51119. for (var index = 0; index < this._animatables.length; index++) {
  51120. var animatable = this._animatables[index];
  51121. animatable.restart();
  51122. }
  51123. return this;
  51124. };
  51125. /**
  51126. * Stop all animations
  51127. */
  51128. AnimationGroup.prototype.stop = function () {
  51129. if (!this._isStarted) {
  51130. return this;
  51131. }
  51132. var list = this._animatables.slice();
  51133. for (var index = 0; index < list.length; index++) {
  51134. list[index].stop();
  51135. }
  51136. this._isStarted = false;
  51137. return this;
  51138. };
  51139. /**
  51140. * Set animation weight for all animatables
  51141. * @param weight defines the weight to use
  51142. * @return the animationGroup
  51143. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51144. */
  51145. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51146. for (var index = 0; index < this._animatables.length; index++) {
  51147. var animatable = this._animatables[index];
  51148. animatable.weight = weight;
  51149. }
  51150. return this;
  51151. };
  51152. /**
  51153. * Synchronize and normalize all animatables with a source animatable
  51154. * @param root defines the root animatable to synchronize with
  51155. * @return the animationGroup
  51156. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51157. */
  51158. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51159. for (var index = 0; index < this._animatables.length; index++) {
  51160. var animatable = this._animatables[index];
  51161. animatable.syncWith(root);
  51162. }
  51163. return this;
  51164. };
  51165. /**
  51166. * Goes to a specific frame in this animation group
  51167. * @param frame the frame number to go to
  51168. * @return the animationGroup
  51169. */
  51170. AnimationGroup.prototype.goToFrame = function (frame) {
  51171. if (!this._isStarted) {
  51172. return this;
  51173. }
  51174. for (var index = 0; index < this._animatables.length; index++) {
  51175. var animatable = this._animatables[index];
  51176. animatable.goToFrame(frame);
  51177. }
  51178. return this;
  51179. };
  51180. /**
  51181. * Dispose all associated resources
  51182. */
  51183. AnimationGroup.prototype.dispose = function () {
  51184. this._targetedAnimations = [];
  51185. this._animatables = [];
  51186. var index = this._scene.animationGroups.indexOf(this);
  51187. if (index > -1) {
  51188. this._scene.animationGroups.splice(index, 1);
  51189. }
  51190. };
  51191. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51192. // animatable should be taken out of the array
  51193. var idx = this._animatables.indexOf(animatable);
  51194. if (idx > -1) {
  51195. this._animatables.splice(idx, 1);
  51196. }
  51197. // all animatables were removed? animation group ended!
  51198. if (this._animatables.length === 0) {
  51199. this._isStarted = false;
  51200. this.onAnimationGroupEndObservable.notifyObservers(this);
  51201. }
  51202. };
  51203. return AnimationGroup;
  51204. }());
  51205. BABYLON.AnimationGroup = AnimationGroup;
  51206. })(BABYLON || (BABYLON = {}));
  51207. //# sourceMappingURL=babylon.animationGroup.js.map
  51208. var BABYLON;
  51209. (function (BABYLON) {
  51210. /**
  51211. * Defines a runtime animation
  51212. */
  51213. var RuntimeAnimation = /** @class */ (function () {
  51214. /**
  51215. * Create a new RuntimeAnimation object
  51216. * @param target defines the target of the animation
  51217. * @param animation defines the source animation object
  51218. * @param scene defines the hosting scene
  51219. * @param host defines the initiating Animatable
  51220. */
  51221. function RuntimeAnimation(target, animation, scene, host) {
  51222. var _this = this;
  51223. this._events = new Array();
  51224. /**
  51225. * The current frame of the runtime animation
  51226. */
  51227. this._currentFrame = 0;
  51228. /**
  51229. * The original value of the runtime animation
  51230. */
  51231. this._originalValue = new Array();
  51232. /**
  51233. * The offsets cache of the runtime animation
  51234. */
  51235. this._offsetsCache = {};
  51236. /**
  51237. * The high limits cache of the runtime animation
  51238. */
  51239. this._highLimitsCache = {};
  51240. /**
  51241. * Specifies if the runtime animation has been stopped
  51242. */
  51243. this._stopped = false;
  51244. /**
  51245. * The blending factor of the runtime animation
  51246. */
  51247. this._blendingFactor = 0;
  51248. /**
  51249. * The target path of the runtime animation
  51250. */
  51251. this._targetPath = "";
  51252. /**
  51253. * The weight of the runtime animation
  51254. */
  51255. this._weight = 1.0;
  51256. /**
  51257. * The ratio offset of the runtime animation
  51258. */
  51259. this._ratioOffset = 0;
  51260. /**
  51261. * The previous delay of the runtime animation
  51262. */
  51263. this._previousDelay = 0;
  51264. /**
  51265. * The previous ratio of the runtime animation
  51266. */
  51267. this._previousRatio = 0;
  51268. this._animation = animation;
  51269. this._target = target;
  51270. this._scene = scene;
  51271. this._host = host;
  51272. animation._runtimeAnimations.push(this);
  51273. // Cloning events locally
  51274. var events = animation.getEvents();
  51275. if (events && events.length > 0) {
  51276. events.forEach(function (e) {
  51277. _this._events.push(e._clone());
  51278. });
  51279. }
  51280. }
  51281. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51282. /**
  51283. * Gets the current frame of the runtime animation
  51284. */
  51285. get: function () {
  51286. return this._currentFrame;
  51287. },
  51288. enumerable: true,
  51289. configurable: true
  51290. });
  51291. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51292. /**
  51293. * Gets the weight of the runtime animation
  51294. */
  51295. get: function () {
  51296. return this._weight;
  51297. },
  51298. enumerable: true,
  51299. configurable: true
  51300. });
  51301. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51302. /**
  51303. * Gets the current value of the runtime animation
  51304. */
  51305. get: function () {
  51306. return this._currentValue;
  51307. },
  51308. enumerable: true,
  51309. configurable: true
  51310. });
  51311. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51312. /**
  51313. * Gets the target path of the runtime animation
  51314. */
  51315. get: function () {
  51316. return this._targetPath;
  51317. },
  51318. enumerable: true,
  51319. configurable: true
  51320. });
  51321. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51322. /**
  51323. * Gets the actual target of the runtime animation
  51324. */
  51325. get: function () {
  51326. return this._activeTarget;
  51327. },
  51328. enumerable: true,
  51329. configurable: true
  51330. });
  51331. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51332. /**
  51333. * Gets the animation from the runtime animation
  51334. */
  51335. get: function () {
  51336. return this._animation;
  51337. },
  51338. enumerable: true,
  51339. configurable: true
  51340. });
  51341. /**
  51342. * Resets the runtime animation to the beginning
  51343. * @param restoreOriginal defines whether to restore the target property to the original value
  51344. */
  51345. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51346. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51347. if (restoreOriginal) {
  51348. if (this._target instanceof Array) {
  51349. var index = 0;
  51350. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51351. var target = _a[_i];
  51352. if (this._originalValue[index] !== undefined) {
  51353. this._setValue(target, this._originalValue[index], -1);
  51354. }
  51355. index++;
  51356. }
  51357. }
  51358. else {
  51359. if (this._originalValue[0] !== undefined) {
  51360. this._setValue(this._target, this._originalValue[0], -1);
  51361. }
  51362. }
  51363. }
  51364. this._offsetsCache = {};
  51365. this._highLimitsCache = {};
  51366. this._currentFrame = 0;
  51367. this._blendingFactor = 0;
  51368. this._originalValue = new Array();
  51369. // Events
  51370. for (var index = 0; index < this._events.length; index++) {
  51371. this._events[index].isDone = false;
  51372. }
  51373. };
  51374. /**
  51375. * Specifies if the runtime animation is stopped
  51376. * @returns Boolean specifying if the runtime animation is stopped
  51377. */
  51378. RuntimeAnimation.prototype.isStopped = function () {
  51379. return this._stopped;
  51380. };
  51381. /**
  51382. * Disposes of the runtime animation
  51383. */
  51384. RuntimeAnimation.prototype.dispose = function () {
  51385. var index = this._animation.runtimeAnimations.indexOf(this);
  51386. if (index > -1) {
  51387. this._animation.runtimeAnimations.splice(index, 1);
  51388. }
  51389. };
  51390. /**
  51391. * Interpolates the animation from the current frame
  51392. * @param currentFrame The frame to interpolate the animation to
  51393. * @param repeatCount The number of times that the animation should loop
  51394. * @param loopMode The type of looping mode to use
  51395. * @param offsetValue Animation offset value
  51396. * @param highLimitValue The high limit value
  51397. * @returns The interpolated value
  51398. */
  51399. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51400. this._currentFrame = currentFrame;
  51401. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51402. this._workValue = BABYLON.Matrix.Zero();
  51403. }
  51404. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51405. };
  51406. /**
  51407. * Apply the interpolated value to the target
  51408. * @param currentValue defines the value computed by the animation
  51409. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51410. */
  51411. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51412. if (weight === void 0) { weight = 1.0; }
  51413. if (this._target instanceof Array) {
  51414. var index = 0;
  51415. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51416. var target = _a[_i];
  51417. this._setValue(target, currentValue, weight, index);
  51418. index++;
  51419. }
  51420. }
  51421. else {
  51422. this._setValue(this._target, currentValue, weight);
  51423. }
  51424. };
  51425. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51426. if (targetIndex === void 0) { targetIndex = 0; }
  51427. // Set value
  51428. var path;
  51429. var destination;
  51430. var targetPropertyPath = this._animation.targetPropertyPath;
  51431. if (targetPropertyPath.length > 1) {
  51432. var property = target[targetPropertyPath[0]];
  51433. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51434. property = property[targetPropertyPath[index]];
  51435. }
  51436. path = targetPropertyPath[targetPropertyPath.length - 1];
  51437. destination = property;
  51438. }
  51439. else {
  51440. path = targetPropertyPath[0];
  51441. destination = target;
  51442. }
  51443. this._targetPath = path;
  51444. this._activeTarget = destination;
  51445. this._weight = weight;
  51446. if (this._originalValue[targetIndex] === undefined) {
  51447. var originalValue = void 0;
  51448. if (destination.getRestPose && path === "_matrix") { // For bones
  51449. originalValue = destination.getRestPose();
  51450. }
  51451. else {
  51452. originalValue = destination[path];
  51453. }
  51454. if (originalValue && originalValue.clone) {
  51455. this._originalValue[targetIndex] = originalValue.clone();
  51456. }
  51457. else {
  51458. this._originalValue[targetIndex] = originalValue;
  51459. }
  51460. }
  51461. // Blending
  51462. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51463. if (enableBlending && this._blendingFactor <= 1.0) {
  51464. if (!this._originalBlendValue) {
  51465. var originalValue = destination[path];
  51466. if (originalValue.clone) {
  51467. this._originalBlendValue = originalValue.clone();
  51468. }
  51469. else {
  51470. this._originalBlendValue = originalValue;
  51471. }
  51472. }
  51473. if (this._originalBlendValue.m) { // Matrix
  51474. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51475. if (this._currentValue) {
  51476. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51477. }
  51478. else {
  51479. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51480. }
  51481. }
  51482. else {
  51483. if (this._currentValue) {
  51484. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51485. }
  51486. else {
  51487. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51488. }
  51489. }
  51490. }
  51491. else {
  51492. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51493. }
  51494. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51495. this._blendingFactor += blendingSpeed;
  51496. }
  51497. else {
  51498. this._currentValue = currentValue;
  51499. }
  51500. if (weight !== -1.0) {
  51501. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51502. }
  51503. else {
  51504. destination[path] = this._currentValue;
  51505. }
  51506. if (target.markAsDirty) {
  51507. target.markAsDirty(this._animation.targetProperty);
  51508. }
  51509. };
  51510. /**
  51511. * Gets the loop pmode of the runtime animation
  51512. * @returns Loop Mode
  51513. */
  51514. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51515. if (this._target && this._target.animationPropertiesOverride) {
  51516. return this._target.animationPropertiesOverride.loopMode;
  51517. }
  51518. return this._animation.loopMode;
  51519. };
  51520. /**
  51521. * Move the current animation to a given frame
  51522. * @param frame defines the frame to move to
  51523. */
  51524. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51525. var keys = this._animation.getKeys();
  51526. if (frame < keys[0].frame) {
  51527. frame = keys[0].frame;
  51528. }
  51529. else if (frame > keys[keys.length - 1].frame) {
  51530. frame = keys[keys.length - 1].frame;
  51531. }
  51532. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51533. this.setValue(currentValue, -1);
  51534. };
  51535. /**
  51536. * @hidden Internal use only
  51537. */
  51538. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51539. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51540. this._ratioOffset = this._previousRatio - newRatio;
  51541. };
  51542. /**
  51543. * Execute the current animation
  51544. * @param delay defines the delay to add to the current frame
  51545. * @param from defines the lower bound of the animation range
  51546. * @param to defines the upper bound of the animation range
  51547. * @param loop defines if the current animation must loop
  51548. * @param speedRatio defines the current speed ratio
  51549. * @param weight defines the weight of the animation (default is -1 so no weight)
  51550. * @returns a boolean indicating if the animation is running
  51551. */
  51552. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51553. if (weight === void 0) { weight = -1.0; }
  51554. var targetPropertyPath = this._animation.targetPropertyPath;
  51555. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51556. this._stopped = true;
  51557. return false;
  51558. }
  51559. var returnValue = true;
  51560. var keys = this._animation.getKeys();
  51561. // Adding a start key at frame 0 if missing
  51562. if (keys[0].frame !== 0) {
  51563. var newKey = { frame: 0, value: keys[0].value };
  51564. keys.splice(0, 0, newKey);
  51565. }
  51566. // Adding a duplicate key when there is only one key at frame zero
  51567. else if (keys.length === 1) {
  51568. var newKey = { frame: 0.001, value: keys[0].value };
  51569. keys.push(newKey);
  51570. }
  51571. // Check limits
  51572. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51573. from = keys[0].frame;
  51574. }
  51575. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51576. to = keys[keys.length - 1].frame;
  51577. }
  51578. //to and from cannot be the same key
  51579. if (from === to) {
  51580. if (from > keys[0].frame) {
  51581. from--;
  51582. }
  51583. else if (to < keys[keys.length - 1].frame) {
  51584. to++;
  51585. }
  51586. }
  51587. // Compute ratio
  51588. var range = to - from;
  51589. var offsetValue;
  51590. // ratio represents the frame delta between from and to
  51591. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51592. var highLimitValue = 0;
  51593. this._previousDelay = delay;
  51594. this._previousRatio = ratio;
  51595. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51596. returnValue = false;
  51597. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51598. }
  51599. else {
  51600. // Get max value if required
  51601. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51602. var keyOffset = to.toString() + from.toString();
  51603. if (!this._offsetsCache[keyOffset]) {
  51604. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51605. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51606. switch (this._animation.dataType) {
  51607. // Float
  51608. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51609. this._offsetsCache[keyOffset] = toValue - fromValue;
  51610. break;
  51611. // Quaternion
  51612. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51613. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51614. break;
  51615. // Vector3
  51616. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51617. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51618. // Vector2
  51619. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51620. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51621. // Size
  51622. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51623. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51624. // Color3
  51625. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51626. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51627. default:
  51628. break;
  51629. }
  51630. this._highLimitsCache[keyOffset] = toValue;
  51631. }
  51632. highLimitValue = this._highLimitsCache[keyOffset];
  51633. offsetValue = this._offsetsCache[keyOffset];
  51634. }
  51635. }
  51636. if (offsetValue === undefined) {
  51637. switch (this._animation.dataType) {
  51638. // Float
  51639. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51640. offsetValue = 0;
  51641. break;
  51642. // Quaternion
  51643. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51644. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51645. break;
  51646. // Vector3
  51647. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51648. offsetValue = BABYLON.Vector3.Zero();
  51649. break;
  51650. // Vector2
  51651. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51652. offsetValue = BABYLON.Vector2.Zero();
  51653. break;
  51654. // Size
  51655. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51656. offsetValue = BABYLON.Size.Zero();
  51657. break;
  51658. // Color3
  51659. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51660. offsetValue = BABYLON.Color3.Black();
  51661. }
  51662. }
  51663. // Compute value
  51664. var repeatCount = (ratio / range) >> 0;
  51665. var currentFrame = returnValue ? from + ratio % range : to;
  51666. // Need to normalize?
  51667. if (this._host && this._host.syncRoot) {
  51668. var syncRoot = this._host.syncRoot;
  51669. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51670. currentFrame = from + (to - from) * hostNormalizedFrame;
  51671. }
  51672. // Reset events if looping
  51673. var events = this._events;
  51674. if (range > 0 && this.currentFrame > currentFrame ||
  51675. range < 0 && this.currentFrame < currentFrame) {
  51676. // Need to reset animation events
  51677. for (var index = 0; index < events.length; index++) {
  51678. if (!events[index].onlyOnce) {
  51679. // reset event, the animation is looping
  51680. events[index].isDone = false;
  51681. }
  51682. }
  51683. }
  51684. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51685. // Set value
  51686. this.setValue(currentValue, weight);
  51687. // Check events
  51688. for (var index = 0; index < events.length; index++) {
  51689. // Make sure current frame has passed event frame and that event frame is within the current range
  51690. // Also, handle both forward and reverse animations
  51691. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51692. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51693. var event = events[index];
  51694. if (!event.isDone) {
  51695. // If event should be done only once, remove it.
  51696. if (event.onlyOnce) {
  51697. events.splice(index, 1);
  51698. index--;
  51699. }
  51700. event.isDone = true;
  51701. event.action(currentFrame);
  51702. } // Don't do anything if the event has already be done.
  51703. }
  51704. }
  51705. if (!returnValue) {
  51706. this._stopped = true;
  51707. }
  51708. return returnValue;
  51709. };
  51710. return RuntimeAnimation;
  51711. }());
  51712. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51713. })(BABYLON || (BABYLON = {}));
  51714. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51715. var BABYLON;
  51716. (function (BABYLON) {
  51717. /**
  51718. * Class used to store an actual running animation
  51719. */
  51720. var Animatable = /** @class */ (function () {
  51721. /**
  51722. * Creates a new Animatable
  51723. * @param scene defines the hosting scene
  51724. * @param target defines the target object
  51725. * @param fromFrame defines the starting frame number (default is 0)
  51726. * @param toFrame defines the ending frame number (default is 100)
  51727. * @param loopAnimation defines if the animation must loop (default is false)
  51728. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51729. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51730. * @param animations defines a group of animation to add to the new Animatable
  51731. */
  51732. function Animatable(scene,
  51733. /** defines the target object */
  51734. target,
  51735. /** defines the starting frame number (default is 0) */
  51736. fromFrame,
  51737. /** defines the ending frame number (default is 100) */
  51738. toFrame,
  51739. /** defines if the animation must loop (default is false) */
  51740. loopAnimation, speedRatio,
  51741. /** defines a callback to call when animation ends if it is not looping */
  51742. onAnimationEnd, animations) {
  51743. if (fromFrame === void 0) { fromFrame = 0; }
  51744. if (toFrame === void 0) { toFrame = 100; }
  51745. if (loopAnimation === void 0) { loopAnimation = false; }
  51746. if (speedRatio === void 0) { speedRatio = 1.0; }
  51747. this.target = target;
  51748. this.fromFrame = fromFrame;
  51749. this.toFrame = toFrame;
  51750. this.loopAnimation = loopAnimation;
  51751. this.onAnimationEnd = onAnimationEnd;
  51752. this._localDelayOffset = null;
  51753. this._pausedDelay = null;
  51754. this._runtimeAnimations = new Array();
  51755. this._paused = false;
  51756. this._speedRatio = 1;
  51757. this._weight = -1.0;
  51758. /**
  51759. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51760. * This will only apply for non looping animation (default is true)
  51761. */
  51762. this.disposeOnEnd = true;
  51763. /**
  51764. * Gets a boolean indicating if the animation has started
  51765. */
  51766. this.animationStarted = false;
  51767. /**
  51768. * Observer raised when the animation ends
  51769. */
  51770. this.onAnimationEndObservable = new BABYLON.Observable();
  51771. this._scene = scene;
  51772. if (animations) {
  51773. this.appendAnimations(target, animations);
  51774. }
  51775. this._speedRatio = speedRatio;
  51776. scene._activeAnimatables.push(this);
  51777. }
  51778. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51779. /**
  51780. * Gets the root Animatable used to synchronize and normalize animations
  51781. */
  51782. get: function () {
  51783. return this._syncRoot;
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51789. /**
  51790. * Gets the current frame of the first RuntimeAnimation
  51791. * Used to synchronize Animatables
  51792. */
  51793. get: function () {
  51794. if (this._runtimeAnimations.length === 0) {
  51795. return 0;
  51796. }
  51797. return this._runtimeAnimations[0].currentFrame;
  51798. },
  51799. enumerable: true,
  51800. configurable: true
  51801. });
  51802. Object.defineProperty(Animatable.prototype, "weight", {
  51803. /**
  51804. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51805. */
  51806. get: function () {
  51807. return this._weight;
  51808. },
  51809. set: function (value) {
  51810. if (value === -1) { // -1 is ok and means no weight
  51811. this._weight = -1;
  51812. return;
  51813. }
  51814. // Else weight must be in [0, 1] range
  51815. this._weight = Math.min(Math.max(value, 0), 1.0);
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51821. /**
  51822. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51823. */
  51824. get: function () {
  51825. return this._speedRatio;
  51826. },
  51827. set: function (value) {
  51828. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51829. var animation = this._runtimeAnimations[index];
  51830. animation._prepareForSpeedRatioChange(value);
  51831. }
  51832. this._speedRatio = value;
  51833. },
  51834. enumerable: true,
  51835. configurable: true
  51836. });
  51837. // Methods
  51838. /**
  51839. * Synchronize and normalize current Animatable with a source Animatable
  51840. * This is useful when using animation weights and when animations are not of the same length
  51841. * @param root defines the root Animatable to synchronize with
  51842. * @returns the current Animatable
  51843. */
  51844. Animatable.prototype.syncWith = function (root) {
  51845. this._syncRoot = root;
  51846. if (root) {
  51847. // Make sure this animatable will animate after the root
  51848. var index = this._scene._activeAnimatables.indexOf(this);
  51849. if (index > -1) {
  51850. this._scene._activeAnimatables.splice(index, 1);
  51851. this._scene._activeAnimatables.push(this);
  51852. }
  51853. }
  51854. return this;
  51855. };
  51856. /**
  51857. * Gets the list of runtime animations
  51858. * @returns an array of RuntimeAnimation
  51859. */
  51860. Animatable.prototype.getAnimations = function () {
  51861. return this._runtimeAnimations;
  51862. };
  51863. /**
  51864. * Adds more animations to the current animatable
  51865. * @param target defines the target of the animations
  51866. * @param animations defines the new animations to add
  51867. */
  51868. Animatable.prototype.appendAnimations = function (target, animations) {
  51869. for (var index = 0; index < animations.length; index++) {
  51870. var animation = animations[index];
  51871. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51872. }
  51873. };
  51874. /**
  51875. * Gets the source animation for a specific property
  51876. * @param property defines the propertyu to look for
  51877. * @returns null or the source animation for the given property
  51878. */
  51879. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51880. var runtimeAnimations = this._runtimeAnimations;
  51881. for (var index = 0; index < runtimeAnimations.length; index++) {
  51882. if (runtimeAnimations[index].animation.targetProperty === property) {
  51883. return runtimeAnimations[index].animation;
  51884. }
  51885. }
  51886. return null;
  51887. };
  51888. /**
  51889. * Gets the runtime animation for a specific property
  51890. * @param property defines the propertyu to look for
  51891. * @returns null or the runtime animation for the given property
  51892. */
  51893. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51894. var runtimeAnimations = this._runtimeAnimations;
  51895. for (var index = 0; index < runtimeAnimations.length; index++) {
  51896. if (runtimeAnimations[index].animation.targetProperty === property) {
  51897. return runtimeAnimations[index];
  51898. }
  51899. }
  51900. return null;
  51901. };
  51902. /**
  51903. * Resets the animatable to its original state
  51904. */
  51905. Animatable.prototype.reset = function () {
  51906. var runtimeAnimations = this._runtimeAnimations;
  51907. for (var index = 0; index < runtimeAnimations.length; index++) {
  51908. runtimeAnimations[index].reset(true);
  51909. }
  51910. this._localDelayOffset = null;
  51911. this._pausedDelay = null;
  51912. };
  51913. /**
  51914. * Allows the animatable to blend with current running animations
  51915. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51916. * @param blendingSpeed defines the blending speed to use
  51917. */
  51918. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51919. var runtimeAnimations = this._runtimeAnimations;
  51920. for (var index = 0; index < runtimeAnimations.length; index++) {
  51921. runtimeAnimations[index].animation.enableBlending = true;
  51922. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51923. }
  51924. };
  51925. /**
  51926. * Disable animation blending
  51927. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51928. */
  51929. Animatable.prototype.disableBlending = function () {
  51930. var runtimeAnimations = this._runtimeAnimations;
  51931. for (var index = 0; index < runtimeAnimations.length; index++) {
  51932. runtimeAnimations[index].animation.enableBlending = false;
  51933. }
  51934. };
  51935. /**
  51936. * Jump directly to a given frame
  51937. * @param frame defines the frame to jump to
  51938. */
  51939. Animatable.prototype.goToFrame = function (frame) {
  51940. var runtimeAnimations = this._runtimeAnimations;
  51941. if (runtimeAnimations[0]) {
  51942. var fps = runtimeAnimations[0].animation.framePerSecond;
  51943. var currentFrame = runtimeAnimations[0].currentFrame;
  51944. var adjustTime = frame - currentFrame;
  51945. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51946. if (this._localDelayOffset === null) {
  51947. this._localDelayOffset = 0;
  51948. }
  51949. this._localDelayOffset -= delay;
  51950. }
  51951. for (var index = 0; index < runtimeAnimations.length; index++) {
  51952. runtimeAnimations[index].goToFrame(frame);
  51953. }
  51954. };
  51955. /**
  51956. * Pause the animation
  51957. */
  51958. Animatable.prototype.pause = function () {
  51959. if (this._paused) {
  51960. return;
  51961. }
  51962. this._paused = true;
  51963. };
  51964. /**
  51965. * Restart the animation
  51966. */
  51967. Animatable.prototype.restart = function () {
  51968. this._paused = false;
  51969. };
  51970. Animatable.prototype._raiseOnAnimationEnd = function () {
  51971. if (this.onAnimationEnd) {
  51972. this.onAnimationEnd();
  51973. }
  51974. this.onAnimationEndObservable.notifyObservers(this);
  51975. };
  51976. /**
  51977. * Stop and delete the current animation
  51978. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51979. * @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)
  51980. */
  51981. Animatable.prototype.stop = function (animationName, targetMask) {
  51982. if (animationName || targetMask) {
  51983. var idx = this._scene._activeAnimatables.indexOf(this);
  51984. if (idx > -1) {
  51985. var runtimeAnimations = this._runtimeAnimations;
  51986. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51987. var runtimeAnimation = runtimeAnimations[index];
  51988. if (animationName && runtimeAnimation.animation.name != animationName) {
  51989. continue;
  51990. }
  51991. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51992. continue;
  51993. }
  51994. runtimeAnimation.dispose();
  51995. runtimeAnimations.splice(index, 1);
  51996. }
  51997. if (runtimeAnimations.length == 0) {
  51998. this._scene._activeAnimatables.splice(idx, 1);
  51999. this._raiseOnAnimationEnd();
  52000. }
  52001. }
  52002. }
  52003. else {
  52004. var index = this._scene._activeAnimatables.indexOf(this);
  52005. if (index > -1) {
  52006. this._scene._activeAnimatables.splice(index, 1);
  52007. var runtimeAnimations = this._runtimeAnimations;
  52008. for (var index = 0; index < runtimeAnimations.length; index++) {
  52009. runtimeAnimations[index].dispose();
  52010. }
  52011. this._raiseOnAnimationEnd();
  52012. }
  52013. }
  52014. };
  52015. /**
  52016. * Wait asynchronously for the animation to end
  52017. * @returns a promise which will be fullfilled when the animation ends
  52018. */
  52019. Animatable.prototype.waitAsync = function () {
  52020. var _this = this;
  52021. return new Promise(function (resolve, reject) {
  52022. _this.onAnimationEndObservable.add(function () {
  52023. resolve(_this);
  52024. }, undefined, undefined, _this, true);
  52025. });
  52026. };
  52027. /** @hidden */
  52028. Animatable.prototype._animate = function (delay) {
  52029. if (this._paused) {
  52030. this.animationStarted = false;
  52031. if (this._pausedDelay === null) {
  52032. this._pausedDelay = delay;
  52033. }
  52034. return true;
  52035. }
  52036. if (this._localDelayOffset === null) {
  52037. this._localDelayOffset = delay;
  52038. this._pausedDelay = null;
  52039. }
  52040. else if (this._pausedDelay !== null) {
  52041. this._localDelayOffset += delay - this._pausedDelay;
  52042. this._pausedDelay = null;
  52043. }
  52044. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52045. return true;
  52046. }
  52047. // Animating
  52048. var running = false;
  52049. var runtimeAnimations = this._runtimeAnimations;
  52050. var index;
  52051. for (index = 0; index < runtimeAnimations.length; index++) {
  52052. var animation = runtimeAnimations[index];
  52053. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52054. running = running || isRunning;
  52055. }
  52056. this.animationStarted = running;
  52057. if (!running) {
  52058. if (this.disposeOnEnd) {
  52059. // Remove from active animatables
  52060. index = this._scene._activeAnimatables.indexOf(this);
  52061. this._scene._activeAnimatables.splice(index, 1);
  52062. // Dispose all runtime animations
  52063. for (index = 0; index < runtimeAnimations.length; index++) {
  52064. runtimeAnimations[index].dispose();
  52065. }
  52066. }
  52067. this._raiseOnAnimationEnd();
  52068. if (this.disposeOnEnd) {
  52069. this.onAnimationEnd = null;
  52070. this.onAnimationEndObservable.clear();
  52071. }
  52072. }
  52073. return running;
  52074. };
  52075. return Animatable;
  52076. }());
  52077. BABYLON.Animatable = Animatable;
  52078. })(BABYLON || (BABYLON = {}));
  52079. //# sourceMappingURL=babylon.animatable.js.map
  52080. var BABYLON;
  52081. (function (BABYLON) {
  52082. var EasingFunction = /** @class */ (function () {
  52083. function EasingFunction() {
  52084. // Properties
  52085. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52086. }
  52087. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52088. get: function () {
  52089. return EasingFunction._EASINGMODE_EASEIN;
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52095. get: function () {
  52096. return EasingFunction._EASINGMODE_EASEOUT;
  52097. },
  52098. enumerable: true,
  52099. configurable: true
  52100. });
  52101. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52102. get: function () {
  52103. return EasingFunction._EASINGMODE_EASEINOUT;
  52104. },
  52105. enumerable: true,
  52106. configurable: true
  52107. });
  52108. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52109. var n = Math.min(Math.max(easingMode, 0), 2);
  52110. this._easingMode = n;
  52111. };
  52112. EasingFunction.prototype.getEasingMode = function () {
  52113. return this._easingMode;
  52114. };
  52115. EasingFunction.prototype.easeInCore = function (gradient) {
  52116. throw new Error('You must implement this method');
  52117. };
  52118. EasingFunction.prototype.ease = function (gradient) {
  52119. switch (this._easingMode) {
  52120. case EasingFunction.EASINGMODE_EASEIN:
  52121. return this.easeInCore(gradient);
  52122. case EasingFunction.EASINGMODE_EASEOUT:
  52123. return (1 - this.easeInCore(1 - gradient));
  52124. }
  52125. if (gradient >= 0.5) {
  52126. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52127. }
  52128. return (this.easeInCore(gradient * 2) * 0.5);
  52129. };
  52130. //Statics
  52131. EasingFunction._EASINGMODE_EASEIN = 0;
  52132. EasingFunction._EASINGMODE_EASEOUT = 1;
  52133. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52134. return EasingFunction;
  52135. }());
  52136. BABYLON.EasingFunction = EasingFunction;
  52137. var CircleEase = /** @class */ (function (_super) {
  52138. __extends(CircleEase, _super);
  52139. function CircleEase() {
  52140. return _super !== null && _super.apply(this, arguments) || this;
  52141. }
  52142. CircleEase.prototype.easeInCore = function (gradient) {
  52143. gradient = Math.max(0, Math.min(1, gradient));
  52144. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52145. };
  52146. return CircleEase;
  52147. }(EasingFunction));
  52148. BABYLON.CircleEase = CircleEase;
  52149. var BackEase = /** @class */ (function (_super) {
  52150. __extends(BackEase, _super);
  52151. function BackEase(amplitude) {
  52152. if (amplitude === void 0) { amplitude = 1; }
  52153. var _this = _super.call(this) || this;
  52154. _this.amplitude = amplitude;
  52155. return _this;
  52156. }
  52157. BackEase.prototype.easeInCore = function (gradient) {
  52158. var num = Math.max(0, this.amplitude);
  52159. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52160. };
  52161. return BackEase;
  52162. }(EasingFunction));
  52163. BABYLON.BackEase = BackEase;
  52164. var BounceEase = /** @class */ (function (_super) {
  52165. __extends(BounceEase, _super);
  52166. function BounceEase(bounces, bounciness) {
  52167. if (bounces === void 0) { bounces = 3; }
  52168. if (bounciness === void 0) { bounciness = 2; }
  52169. var _this = _super.call(this) || this;
  52170. _this.bounces = bounces;
  52171. _this.bounciness = bounciness;
  52172. return _this;
  52173. }
  52174. BounceEase.prototype.easeInCore = function (gradient) {
  52175. var y = Math.max(0.0, this.bounces);
  52176. var bounciness = this.bounciness;
  52177. if (bounciness <= 1.0) {
  52178. bounciness = 1.001;
  52179. }
  52180. var num9 = Math.pow(bounciness, y);
  52181. var num5 = 1.0 - bounciness;
  52182. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52183. var num15 = gradient * num4;
  52184. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52185. var num3 = Math.floor(num65);
  52186. var num13 = num3 + 1.0;
  52187. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52188. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52189. var num7 = (num8 + num12) * 0.5;
  52190. var num6 = gradient - num7;
  52191. var num2 = num7 - num8;
  52192. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52193. };
  52194. return BounceEase;
  52195. }(EasingFunction));
  52196. BABYLON.BounceEase = BounceEase;
  52197. var CubicEase = /** @class */ (function (_super) {
  52198. __extends(CubicEase, _super);
  52199. function CubicEase() {
  52200. return _super !== null && _super.apply(this, arguments) || this;
  52201. }
  52202. CubicEase.prototype.easeInCore = function (gradient) {
  52203. return (gradient * gradient * gradient);
  52204. };
  52205. return CubicEase;
  52206. }(EasingFunction));
  52207. BABYLON.CubicEase = CubicEase;
  52208. var ElasticEase = /** @class */ (function (_super) {
  52209. __extends(ElasticEase, _super);
  52210. function ElasticEase(oscillations, springiness) {
  52211. if (oscillations === void 0) { oscillations = 3; }
  52212. if (springiness === void 0) { springiness = 3; }
  52213. var _this = _super.call(this) || this;
  52214. _this.oscillations = oscillations;
  52215. _this.springiness = springiness;
  52216. return _this;
  52217. }
  52218. ElasticEase.prototype.easeInCore = function (gradient) {
  52219. var num2;
  52220. var num3 = Math.max(0.0, this.oscillations);
  52221. var num = Math.max(0.0, this.springiness);
  52222. if (num == 0) {
  52223. num2 = gradient;
  52224. }
  52225. else {
  52226. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52227. }
  52228. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52229. };
  52230. return ElasticEase;
  52231. }(EasingFunction));
  52232. BABYLON.ElasticEase = ElasticEase;
  52233. var ExponentialEase = /** @class */ (function (_super) {
  52234. __extends(ExponentialEase, _super);
  52235. function ExponentialEase(exponent) {
  52236. if (exponent === void 0) { exponent = 2; }
  52237. var _this = _super.call(this) || this;
  52238. _this.exponent = exponent;
  52239. return _this;
  52240. }
  52241. ExponentialEase.prototype.easeInCore = function (gradient) {
  52242. if (this.exponent <= 0) {
  52243. return gradient;
  52244. }
  52245. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52246. };
  52247. return ExponentialEase;
  52248. }(EasingFunction));
  52249. BABYLON.ExponentialEase = ExponentialEase;
  52250. var PowerEase = /** @class */ (function (_super) {
  52251. __extends(PowerEase, _super);
  52252. function PowerEase(power) {
  52253. if (power === void 0) { power = 2; }
  52254. var _this = _super.call(this) || this;
  52255. _this.power = power;
  52256. return _this;
  52257. }
  52258. PowerEase.prototype.easeInCore = function (gradient) {
  52259. var y = Math.max(0.0, this.power);
  52260. return Math.pow(gradient, y);
  52261. };
  52262. return PowerEase;
  52263. }(EasingFunction));
  52264. BABYLON.PowerEase = PowerEase;
  52265. var QuadraticEase = /** @class */ (function (_super) {
  52266. __extends(QuadraticEase, _super);
  52267. function QuadraticEase() {
  52268. return _super !== null && _super.apply(this, arguments) || this;
  52269. }
  52270. QuadraticEase.prototype.easeInCore = function (gradient) {
  52271. return (gradient * gradient);
  52272. };
  52273. return QuadraticEase;
  52274. }(EasingFunction));
  52275. BABYLON.QuadraticEase = QuadraticEase;
  52276. var QuarticEase = /** @class */ (function (_super) {
  52277. __extends(QuarticEase, _super);
  52278. function QuarticEase() {
  52279. return _super !== null && _super.apply(this, arguments) || this;
  52280. }
  52281. QuarticEase.prototype.easeInCore = function (gradient) {
  52282. return (gradient * gradient * gradient * gradient);
  52283. };
  52284. return QuarticEase;
  52285. }(EasingFunction));
  52286. BABYLON.QuarticEase = QuarticEase;
  52287. var QuinticEase = /** @class */ (function (_super) {
  52288. __extends(QuinticEase, _super);
  52289. function QuinticEase() {
  52290. return _super !== null && _super.apply(this, arguments) || this;
  52291. }
  52292. QuinticEase.prototype.easeInCore = function (gradient) {
  52293. return (gradient * gradient * gradient * gradient * gradient);
  52294. };
  52295. return QuinticEase;
  52296. }(EasingFunction));
  52297. BABYLON.QuinticEase = QuinticEase;
  52298. var SineEase = /** @class */ (function (_super) {
  52299. __extends(SineEase, _super);
  52300. function SineEase() {
  52301. return _super !== null && _super.apply(this, arguments) || this;
  52302. }
  52303. SineEase.prototype.easeInCore = function (gradient) {
  52304. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52305. };
  52306. return SineEase;
  52307. }(EasingFunction));
  52308. BABYLON.SineEase = SineEase;
  52309. var BezierCurveEase = /** @class */ (function (_super) {
  52310. __extends(BezierCurveEase, _super);
  52311. function BezierCurveEase(x1, y1, x2, y2) {
  52312. if (x1 === void 0) { x1 = 0; }
  52313. if (y1 === void 0) { y1 = 0; }
  52314. if (x2 === void 0) { x2 = 1; }
  52315. if (y2 === void 0) { y2 = 1; }
  52316. var _this = _super.call(this) || this;
  52317. _this.x1 = x1;
  52318. _this.y1 = y1;
  52319. _this.x2 = x2;
  52320. _this.y2 = y2;
  52321. return _this;
  52322. }
  52323. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52324. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52325. };
  52326. return BezierCurveEase;
  52327. }(EasingFunction));
  52328. BABYLON.BezierCurveEase = BezierCurveEase;
  52329. })(BABYLON || (BABYLON = {}));
  52330. //# sourceMappingURL=babylon.easing.js.map
  52331. var BABYLON;
  52332. (function (BABYLON) {
  52333. /**
  52334. * A Condition applied to an Action
  52335. */
  52336. var Condition = /** @class */ (function () {
  52337. /**
  52338. * Creates a new Condition
  52339. * @param actionManager the manager of the action the condition is applied to
  52340. */
  52341. function Condition(actionManager) {
  52342. this._actionManager = actionManager;
  52343. }
  52344. /**
  52345. * Check if the current condition is valid
  52346. * @returns a boolean
  52347. */
  52348. Condition.prototype.isValid = function () {
  52349. return true;
  52350. };
  52351. /**
  52352. * Internal only
  52353. * @hidden
  52354. */
  52355. Condition.prototype._getProperty = function (propertyPath) {
  52356. return this._actionManager._getProperty(propertyPath);
  52357. };
  52358. /**
  52359. * Internal only
  52360. * @hidden
  52361. */
  52362. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52363. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52364. };
  52365. /**
  52366. * Serialize placeholder for child classes
  52367. * @returns the serialized object
  52368. */
  52369. Condition.prototype.serialize = function () {
  52370. };
  52371. /**
  52372. * Internal only
  52373. * @hidden
  52374. */
  52375. Condition.prototype._serialize = function (serializedCondition) {
  52376. return {
  52377. type: 2,
  52378. children: [],
  52379. name: serializedCondition.name,
  52380. properties: serializedCondition.properties
  52381. };
  52382. };
  52383. return Condition;
  52384. }());
  52385. BABYLON.Condition = Condition;
  52386. /**
  52387. * Defines specific conditional operators as extensions of Condition
  52388. */
  52389. var ValueCondition = /** @class */ (function (_super) {
  52390. __extends(ValueCondition, _super);
  52391. /**
  52392. * Creates a new ValueCondition
  52393. * @param actionManager manager for the action the condition applies to
  52394. * @param target for the action
  52395. * @param propertyPath path to specify the property of the target the conditional operator uses
  52396. * @param value the value compared by the conditional operator against the current value of the property
  52397. * @param operator the conditional operator, default ValueCondition.IsEqual
  52398. */
  52399. function ValueCondition(actionManager, target,
  52400. /** path to specify the property of the target the conditional operator uses */
  52401. propertyPath,
  52402. /** the value compared by the conditional operator against the current value of the property */
  52403. value,
  52404. /** the conditional operator, default ValueCondition.IsEqual */
  52405. operator) {
  52406. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52407. var _this = _super.call(this, actionManager) || this;
  52408. _this.propertyPath = propertyPath;
  52409. _this.value = value;
  52410. _this.operator = operator;
  52411. _this._target = target;
  52412. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52413. _this._property = _this._getProperty(_this.propertyPath);
  52414. return _this;
  52415. }
  52416. Object.defineProperty(ValueCondition, "IsEqual", {
  52417. /**
  52418. * returns the number for IsEqual
  52419. */
  52420. get: function () {
  52421. return ValueCondition._IsEqual;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(ValueCondition, "IsDifferent", {
  52427. /**
  52428. * Returns the number for IsDifferent
  52429. */
  52430. get: function () {
  52431. return ValueCondition._IsDifferent;
  52432. },
  52433. enumerable: true,
  52434. configurable: true
  52435. });
  52436. Object.defineProperty(ValueCondition, "IsGreater", {
  52437. /**
  52438. * Returns the number for IsGreater
  52439. */
  52440. get: function () {
  52441. return ValueCondition._IsGreater;
  52442. },
  52443. enumerable: true,
  52444. configurable: true
  52445. });
  52446. Object.defineProperty(ValueCondition, "IsLesser", {
  52447. /**
  52448. * Returns the number for IsLesser
  52449. */
  52450. get: function () {
  52451. return ValueCondition._IsLesser;
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. /**
  52457. * Compares the given value with the property value for the specified conditional operator
  52458. * @returns the result of the comparison
  52459. */
  52460. ValueCondition.prototype.isValid = function () {
  52461. switch (this.operator) {
  52462. case ValueCondition.IsGreater:
  52463. return this._effectiveTarget[this._property] > this.value;
  52464. case ValueCondition.IsLesser:
  52465. return this._effectiveTarget[this._property] < this.value;
  52466. case ValueCondition.IsEqual:
  52467. case ValueCondition.IsDifferent:
  52468. var check;
  52469. if (this.value.equals) {
  52470. check = this.value.equals(this._effectiveTarget[this._property]);
  52471. }
  52472. else {
  52473. check = this.value === this._effectiveTarget[this._property];
  52474. }
  52475. return this.operator === ValueCondition.IsEqual ? check : !check;
  52476. }
  52477. return false;
  52478. };
  52479. /**
  52480. * Serialize the ValueCondition into a JSON compatible object
  52481. * @returns serialization object
  52482. */
  52483. ValueCondition.prototype.serialize = function () {
  52484. return this._serialize({
  52485. name: "ValueCondition",
  52486. properties: [
  52487. BABYLON.Action._GetTargetProperty(this._target),
  52488. { name: "propertyPath", value: this.propertyPath },
  52489. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52490. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52491. ]
  52492. });
  52493. };
  52494. /**
  52495. * Gets the name of the conditional operator for the ValueCondition
  52496. * @param operator the conditional operator
  52497. * @returns the name
  52498. */
  52499. ValueCondition.GetOperatorName = function (operator) {
  52500. switch (operator) {
  52501. case ValueCondition._IsEqual: return "IsEqual";
  52502. case ValueCondition._IsDifferent: return "IsDifferent";
  52503. case ValueCondition._IsGreater: return "IsGreater";
  52504. case ValueCondition._IsLesser: return "IsLesser";
  52505. default: return "";
  52506. }
  52507. };
  52508. /**
  52509. * Internal only
  52510. * @hidden
  52511. */
  52512. ValueCondition._IsEqual = 0;
  52513. /**
  52514. * Internal only
  52515. * @hidden
  52516. */
  52517. ValueCondition._IsDifferent = 1;
  52518. /**
  52519. * Internal only
  52520. * @hidden
  52521. */
  52522. ValueCondition._IsGreater = 2;
  52523. /**
  52524. * Internal only
  52525. * @hidden
  52526. */
  52527. ValueCondition._IsLesser = 3;
  52528. return ValueCondition;
  52529. }(Condition));
  52530. BABYLON.ValueCondition = ValueCondition;
  52531. /**
  52532. * Defines a predicate condition as an extension of Condition
  52533. */
  52534. var PredicateCondition = /** @class */ (function (_super) {
  52535. __extends(PredicateCondition, _super);
  52536. /**
  52537. * Creates a new PredicateCondition
  52538. * @param actionManager manager for the action the condition applies to
  52539. * @param predicate defines the predicate function used to validate the condition
  52540. */
  52541. function PredicateCondition(actionManager,
  52542. /** defines the predicate function used to validate the condition */
  52543. predicate) {
  52544. var _this = _super.call(this, actionManager) || this;
  52545. _this.predicate = predicate;
  52546. return _this;
  52547. }
  52548. /**
  52549. * @returns the validity of the predicate condition
  52550. */
  52551. PredicateCondition.prototype.isValid = function () {
  52552. return this.predicate();
  52553. };
  52554. return PredicateCondition;
  52555. }(Condition));
  52556. BABYLON.PredicateCondition = PredicateCondition;
  52557. /**
  52558. * Defines a state condition as an extension of Condition
  52559. */
  52560. var StateCondition = /** @class */ (function (_super) {
  52561. __extends(StateCondition, _super);
  52562. /**
  52563. * Creates a new StateCondition
  52564. * @param actionManager manager for the action the condition applies to
  52565. * @param target of the condition
  52566. * @param value to compare with target state
  52567. */
  52568. function StateCondition(actionManager, target, value) {
  52569. var _this = _super.call(this, actionManager) || this;
  52570. _this.value = value;
  52571. _this._target = target;
  52572. return _this;
  52573. }
  52574. /**
  52575. * @returns the validity of the state
  52576. */
  52577. StateCondition.prototype.isValid = function () {
  52578. return this._target.state === this.value;
  52579. };
  52580. /**
  52581. * Serialize the StateCondition into a JSON compatible object
  52582. * @returns serialization object
  52583. */
  52584. StateCondition.prototype.serialize = function () {
  52585. return this._serialize({
  52586. name: "StateCondition",
  52587. properties: [
  52588. BABYLON.Action._GetTargetProperty(this._target),
  52589. { name: "value", value: this.value }
  52590. ]
  52591. });
  52592. };
  52593. return StateCondition;
  52594. }(Condition));
  52595. BABYLON.StateCondition = StateCondition;
  52596. })(BABYLON || (BABYLON = {}));
  52597. //# sourceMappingURL=babylon.condition.js.map
  52598. var BABYLON;
  52599. (function (BABYLON) {
  52600. /**
  52601. * The action to be carried out following a trigger
  52602. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52603. */
  52604. var Action = /** @class */ (function () {
  52605. /**
  52606. * Creates a new Action
  52607. * @param triggerOptions the trigger, with or without parameters, for the action
  52608. * @param condition an optional determinant of action
  52609. */
  52610. function Action(
  52611. /** the trigger, with or without parameters, for the action */
  52612. triggerOptions, condition) {
  52613. this.triggerOptions = triggerOptions;
  52614. /**
  52615. * An event triggered prior to action being executed.
  52616. */
  52617. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52618. if (triggerOptions.parameter) {
  52619. this.trigger = triggerOptions.trigger;
  52620. this._triggerParameter = triggerOptions.parameter;
  52621. }
  52622. else {
  52623. this.trigger = triggerOptions;
  52624. }
  52625. this._nextActiveAction = this;
  52626. this._condition = condition;
  52627. }
  52628. /**
  52629. * Internal only
  52630. * @hidden
  52631. */
  52632. Action.prototype._prepare = function () {
  52633. };
  52634. /**
  52635. * Gets the trigger parameters
  52636. * @returns the trigger parameters
  52637. */
  52638. Action.prototype.getTriggerParameter = function () {
  52639. return this._triggerParameter;
  52640. };
  52641. /**
  52642. * Internal only - executes current action event
  52643. * @hidden
  52644. */
  52645. Action.prototype._executeCurrent = function (evt) {
  52646. if (this._nextActiveAction._condition) {
  52647. var condition = this._nextActiveAction._condition;
  52648. var currentRenderId = this._actionManager.getScene().getRenderId();
  52649. // We cache the current evaluation for the current frame
  52650. if (condition._evaluationId === currentRenderId) {
  52651. if (!condition._currentResult) {
  52652. return;
  52653. }
  52654. }
  52655. else {
  52656. condition._evaluationId = currentRenderId;
  52657. if (!condition.isValid()) {
  52658. condition._currentResult = false;
  52659. return;
  52660. }
  52661. condition._currentResult = true;
  52662. }
  52663. }
  52664. this.onBeforeExecuteObservable.notifyObservers(this);
  52665. this._nextActiveAction.execute(evt);
  52666. this.skipToNextActiveAction();
  52667. };
  52668. /**
  52669. * Execute placeholder for child classes
  52670. * @param evt optional action event
  52671. */
  52672. Action.prototype.execute = function (evt) {
  52673. };
  52674. /**
  52675. * Skips to next active action
  52676. */
  52677. Action.prototype.skipToNextActiveAction = function () {
  52678. if (this._nextActiveAction._child) {
  52679. if (!this._nextActiveAction._child._actionManager) {
  52680. this._nextActiveAction._child._actionManager = this._actionManager;
  52681. }
  52682. this._nextActiveAction = this._nextActiveAction._child;
  52683. }
  52684. else {
  52685. this._nextActiveAction = this;
  52686. }
  52687. };
  52688. /**
  52689. * Adds action to chain of actions, may be a DoNothingAction
  52690. * @param action defines the next action to execute
  52691. * @returns The action passed in
  52692. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52693. */
  52694. Action.prototype.then = function (action) {
  52695. this._child = action;
  52696. action._actionManager = this._actionManager;
  52697. action._prepare();
  52698. return action;
  52699. };
  52700. /**
  52701. * Internal only
  52702. * @hidden
  52703. */
  52704. Action.prototype._getProperty = function (propertyPath) {
  52705. return this._actionManager._getProperty(propertyPath);
  52706. };
  52707. /**
  52708. * Internal only
  52709. * @hidden
  52710. */
  52711. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52712. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52713. };
  52714. /**
  52715. * Serialize placeholder for child classes
  52716. * @param parent of child
  52717. * @returns the serialized object
  52718. */
  52719. Action.prototype.serialize = function (parent) {
  52720. };
  52721. /**
  52722. * Internal only called by serialize
  52723. * @hidden
  52724. */
  52725. Action.prototype._serialize = function (serializedAction, parent) {
  52726. var serializationObject = {
  52727. type: 1,
  52728. children: [],
  52729. name: serializedAction.name,
  52730. properties: serializedAction.properties || []
  52731. };
  52732. // Serialize child
  52733. if (this._child) {
  52734. this._child.serialize(serializationObject);
  52735. }
  52736. // Check if "this" has a condition
  52737. if (this._condition) {
  52738. var serializedCondition = this._condition.serialize();
  52739. serializedCondition.children.push(serializationObject);
  52740. if (parent) {
  52741. parent.children.push(serializedCondition);
  52742. }
  52743. return serializedCondition;
  52744. }
  52745. if (parent) {
  52746. parent.children.push(serializationObject);
  52747. }
  52748. return serializationObject;
  52749. };
  52750. /**
  52751. * Internal only
  52752. * @hidden
  52753. */
  52754. Action._SerializeValueAsString = function (value) {
  52755. if (typeof value === "number") {
  52756. return value.toString();
  52757. }
  52758. if (typeof value === "boolean") {
  52759. return value ? "true" : "false";
  52760. }
  52761. if (value instanceof BABYLON.Vector2) {
  52762. return value.x + ", " + value.y;
  52763. }
  52764. if (value instanceof BABYLON.Vector3) {
  52765. return value.x + ", " + value.y + ", " + value.z;
  52766. }
  52767. if (value instanceof BABYLON.Color3) {
  52768. return value.r + ", " + value.g + ", " + value.b;
  52769. }
  52770. if (value instanceof BABYLON.Color4) {
  52771. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52772. }
  52773. return value; // string
  52774. };
  52775. /**
  52776. * Internal only
  52777. * @hidden
  52778. */
  52779. Action._GetTargetProperty = function (target) {
  52780. return {
  52781. name: "target",
  52782. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52783. : target instanceof BABYLON.Light ? "LightProperties"
  52784. : target instanceof BABYLON.Camera ? "CameraProperties"
  52785. : "SceneProperties",
  52786. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52787. };
  52788. };
  52789. return Action;
  52790. }());
  52791. BABYLON.Action = Action;
  52792. })(BABYLON || (BABYLON = {}));
  52793. //# sourceMappingURL=babylon.action.js.map
  52794. var BABYLON;
  52795. (function (BABYLON) {
  52796. /**
  52797. * ActionEvent is the event being sent when an action is triggered.
  52798. */
  52799. var ActionEvent = /** @class */ (function () {
  52800. /**
  52801. * Creates a new ActionEvent
  52802. * @param source The mesh or sprite that triggered the action
  52803. * @param pointerX The X mouse cursor position at the time of the event
  52804. * @param pointerY The Y mouse cursor position at the time of the event
  52805. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52806. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52807. * @param additionalData additional data for the event
  52808. */
  52809. function ActionEvent(
  52810. /** The mesh or sprite that triggered the action */
  52811. source,
  52812. /** The X mouse cursor position at the time of the event */
  52813. pointerX,
  52814. /** The Y mouse cursor position at the time of the event */
  52815. pointerY,
  52816. /** The mesh that is currently pointed at (can be null) */
  52817. meshUnderPointer,
  52818. /** the original (browser) event that triggered the ActionEvent */
  52819. sourceEvent,
  52820. /** additional data for the event */
  52821. additionalData) {
  52822. this.source = source;
  52823. this.pointerX = pointerX;
  52824. this.pointerY = pointerY;
  52825. this.meshUnderPointer = meshUnderPointer;
  52826. this.sourceEvent = sourceEvent;
  52827. this.additionalData = additionalData;
  52828. }
  52829. /**
  52830. * Helper function to auto-create an ActionEvent from a source mesh.
  52831. * @param source The source mesh that triggered the event
  52832. * @param evt The original (browser) event
  52833. * @param additionalData additional data for the event
  52834. * @returns the new ActionEvent
  52835. */
  52836. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52837. var scene = source.getScene();
  52838. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52839. };
  52840. /**
  52841. * Helper function to auto-create an ActionEvent from a source sprite
  52842. * @param source The source sprite that triggered the event
  52843. * @param scene Scene associated with the sprite
  52844. * @param evt The original (browser) event
  52845. * @param additionalData additional data for the event
  52846. * @returns the new ActionEvent
  52847. */
  52848. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52849. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52850. };
  52851. /**
  52852. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52853. * @param scene the scene where the event occurred
  52854. * @param evt The original (browser) event
  52855. * @returns the new ActionEvent
  52856. */
  52857. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52858. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52859. };
  52860. /**
  52861. * Helper function to auto-create an ActionEvent from a primitive
  52862. * @param prim defines the target primitive
  52863. * @param pointerPos defines the pointer position
  52864. * @param evt The original (browser) event
  52865. * @param additionalData additional data for the event
  52866. * @returns the new ActionEvent
  52867. */
  52868. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52869. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52870. };
  52871. return ActionEvent;
  52872. }());
  52873. BABYLON.ActionEvent = ActionEvent;
  52874. /**
  52875. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52876. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52877. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52878. */
  52879. var ActionManager = /** @class */ (function () {
  52880. /**
  52881. * Creates a new action manager
  52882. * @param scene defines the hosting scene
  52883. */
  52884. function ActionManager(scene) {
  52885. // Members
  52886. /** Gets the list of actions */
  52887. this.actions = new Array();
  52888. /** Gets the cursor to use when hovering items */
  52889. this.hoverCursor = '';
  52890. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52891. scene.actionManagers.push(this);
  52892. }
  52893. Object.defineProperty(ActionManager, "NothingTrigger", {
  52894. /**
  52895. * Nothing
  52896. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52897. */
  52898. get: function () {
  52899. return ActionManager._NothingTrigger;
  52900. },
  52901. enumerable: true,
  52902. configurable: true
  52903. });
  52904. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52905. /**
  52906. * On pick
  52907. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52908. */
  52909. get: function () {
  52910. return ActionManager._OnPickTrigger;
  52911. },
  52912. enumerable: true,
  52913. configurable: true
  52914. });
  52915. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52916. /**
  52917. * On left pick
  52918. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52919. */
  52920. get: function () {
  52921. return ActionManager._OnLeftPickTrigger;
  52922. },
  52923. enumerable: true,
  52924. configurable: true
  52925. });
  52926. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52927. /**
  52928. * On right pick
  52929. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52930. */
  52931. get: function () {
  52932. return ActionManager._OnRightPickTrigger;
  52933. },
  52934. enumerable: true,
  52935. configurable: true
  52936. });
  52937. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52938. /**
  52939. * On center pick
  52940. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52941. */
  52942. get: function () {
  52943. return ActionManager._OnCenterPickTrigger;
  52944. },
  52945. enumerable: true,
  52946. configurable: true
  52947. });
  52948. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52949. /**
  52950. * On pick down
  52951. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52952. */
  52953. get: function () {
  52954. return ActionManager._OnPickDownTrigger;
  52955. },
  52956. enumerable: true,
  52957. configurable: true
  52958. });
  52959. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52960. /**
  52961. * On double pick
  52962. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52963. */
  52964. get: function () {
  52965. return ActionManager._OnDoublePickTrigger;
  52966. },
  52967. enumerable: true,
  52968. configurable: true
  52969. });
  52970. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52971. /**
  52972. * On pick up
  52973. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52974. */
  52975. get: function () {
  52976. return ActionManager._OnPickUpTrigger;
  52977. },
  52978. enumerable: true,
  52979. configurable: true
  52980. });
  52981. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52982. /**
  52983. * On pick out.
  52984. * This trigger will only be raised if you also declared a OnPickDown
  52985. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52986. */
  52987. get: function () {
  52988. return ActionManager._OnPickOutTrigger;
  52989. },
  52990. enumerable: true,
  52991. configurable: true
  52992. });
  52993. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52994. /**
  52995. * On long press
  52996. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52997. */
  52998. get: function () {
  52999. return ActionManager._OnLongPressTrigger;
  53000. },
  53001. enumerable: true,
  53002. configurable: true
  53003. });
  53004. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53005. /**
  53006. * On pointer over
  53007. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53008. */
  53009. get: function () {
  53010. return ActionManager._OnPointerOverTrigger;
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53016. /**
  53017. * On pointer out
  53018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53019. */
  53020. get: function () {
  53021. return ActionManager._OnPointerOutTrigger;
  53022. },
  53023. enumerable: true,
  53024. configurable: true
  53025. });
  53026. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53027. /**
  53028. * On every frame
  53029. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53030. */
  53031. get: function () {
  53032. return ActionManager._OnEveryFrameTrigger;
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53038. /**
  53039. * On intersection enter
  53040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53041. */
  53042. get: function () {
  53043. return ActionManager._OnIntersectionEnterTrigger;
  53044. },
  53045. enumerable: true,
  53046. configurable: true
  53047. });
  53048. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53049. /**
  53050. * On intersection exit
  53051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53052. */
  53053. get: function () {
  53054. return ActionManager._OnIntersectionExitTrigger;
  53055. },
  53056. enumerable: true,
  53057. configurable: true
  53058. });
  53059. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53060. /**
  53061. * On key down
  53062. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53063. */
  53064. get: function () {
  53065. return ActionManager._OnKeyDownTrigger;
  53066. },
  53067. enumerable: true,
  53068. configurable: true
  53069. });
  53070. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53071. /**
  53072. * On key up
  53073. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53074. */
  53075. get: function () {
  53076. return ActionManager._OnKeyUpTrigger;
  53077. },
  53078. enumerable: true,
  53079. configurable: true
  53080. });
  53081. // Methods
  53082. /**
  53083. * Releases all associated resources
  53084. */
  53085. ActionManager.prototype.dispose = function () {
  53086. var index = this._scene.actionManagers.indexOf(this);
  53087. for (var i = 0; i < this.actions.length; i++) {
  53088. var action = this.actions[i];
  53089. ActionManager.Triggers[action.trigger]--;
  53090. if (ActionManager.Triggers[action.trigger] === 0) {
  53091. delete ActionManager.Triggers[action.trigger];
  53092. }
  53093. }
  53094. if (index > -1) {
  53095. this._scene.actionManagers.splice(index, 1);
  53096. }
  53097. };
  53098. /**
  53099. * Gets hosting scene
  53100. * @returns the hosting scene
  53101. */
  53102. ActionManager.prototype.getScene = function () {
  53103. return this._scene;
  53104. };
  53105. /**
  53106. * Does this action manager handles actions of any of the given triggers
  53107. * @param triggers defines the triggers to be tested
  53108. * @return a boolean indicating whether one (or more) of the triggers is handled
  53109. */
  53110. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53111. for (var index = 0; index < this.actions.length; index++) {
  53112. var action = this.actions[index];
  53113. if (triggers.indexOf(action.trigger) > -1) {
  53114. return true;
  53115. }
  53116. }
  53117. return false;
  53118. };
  53119. /**
  53120. * Does this action manager handles actions of a given trigger
  53121. * @param trigger defines the trigger to be tested
  53122. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53123. * @return whether the trigger is handled
  53124. */
  53125. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53126. for (var index = 0; index < this.actions.length; index++) {
  53127. var action = this.actions[index];
  53128. if (action.trigger === trigger) {
  53129. if (parameterPredicate) {
  53130. if (parameterPredicate(action.getTriggerParameter())) {
  53131. return true;
  53132. }
  53133. }
  53134. else {
  53135. return true;
  53136. }
  53137. }
  53138. }
  53139. return false;
  53140. };
  53141. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53142. /**
  53143. * Does this action manager has pointer triggers
  53144. */
  53145. get: function () {
  53146. for (var index = 0; index < this.actions.length; index++) {
  53147. var action = this.actions[index];
  53148. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53149. return true;
  53150. }
  53151. }
  53152. return false;
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53158. /**
  53159. * Does this action manager has pick triggers
  53160. */
  53161. get: function () {
  53162. for (var index = 0; index < this.actions.length; index++) {
  53163. var action = this.actions[index];
  53164. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53165. return true;
  53166. }
  53167. }
  53168. return false;
  53169. },
  53170. enumerable: true,
  53171. configurable: true
  53172. });
  53173. Object.defineProperty(ActionManager, "HasTriggers", {
  53174. /**
  53175. * Does exist one action manager with at least one trigger
  53176. **/
  53177. get: function () {
  53178. for (var t in ActionManager.Triggers) {
  53179. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53180. return true;
  53181. }
  53182. }
  53183. return false;
  53184. },
  53185. enumerable: true,
  53186. configurable: true
  53187. });
  53188. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53189. /**
  53190. * Does exist one action manager with at least one pick trigger
  53191. **/
  53192. get: function () {
  53193. for (var t in ActionManager.Triggers) {
  53194. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53195. var t_int = parseInt(t);
  53196. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53197. return true;
  53198. }
  53199. }
  53200. }
  53201. return false;
  53202. },
  53203. enumerable: true,
  53204. configurable: true
  53205. });
  53206. /**
  53207. * Does exist one action manager that handles actions of a given trigger
  53208. * @param trigger defines the trigger to be tested
  53209. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53210. **/
  53211. ActionManager.HasSpecificTrigger = function (trigger) {
  53212. for (var t in ActionManager.Triggers) {
  53213. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53214. var t_int = parseInt(t);
  53215. if (t_int === trigger) {
  53216. return true;
  53217. }
  53218. }
  53219. }
  53220. return false;
  53221. };
  53222. /**
  53223. * Registers an action to this action manager
  53224. * @param action defines the action to be registered
  53225. * @return the action amended (prepared) after registration
  53226. */
  53227. ActionManager.prototype.registerAction = function (action) {
  53228. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53229. if (this.getScene().actionManager !== this) {
  53230. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53231. return null;
  53232. }
  53233. }
  53234. this.actions.push(action);
  53235. if (ActionManager.Triggers[action.trigger]) {
  53236. ActionManager.Triggers[action.trigger]++;
  53237. }
  53238. else {
  53239. ActionManager.Triggers[action.trigger] = 1;
  53240. }
  53241. action._actionManager = this;
  53242. action._prepare();
  53243. return action;
  53244. };
  53245. /**
  53246. * Unregisters an action to this action manager
  53247. * @param action defines the action to be unregistered
  53248. * @return a boolean indicating whether the action has been unregistered
  53249. */
  53250. ActionManager.prototype.unregisterAction = function (action) {
  53251. var index = this.actions.indexOf(action);
  53252. if (index !== -1) {
  53253. this.actions.splice(index, 1);
  53254. ActionManager.Triggers[action.trigger] -= 1;
  53255. if (ActionManager.Triggers[action.trigger] === 0) {
  53256. delete ActionManager.Triggers[action.trigger];
  53257. }
  53258. delete action._actionManager;
  53259. return true;
  53260. }
  53261. return false;
  53262. };
  53263. /**
  53264. * Process a specific trigger
  53265. * @param trigger defines the trigger to process
  53266. * @param evt defines the event details to be processed
  53267. */
  53268. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53269. for (var index = 0; index < this.actions.length; index++) {
  53270. var action = this.actions[index];
  53271. if (action.trigger === trigger) {
  53272. if (evt) {
  53273. if (trigger === ActionManager.OnKeyUpTrigger
  53274. || trigger === ActionManager.OnKeyDownTrigger) {
  53275. var parameter = action.getTriggerParameter();
  53276. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53277. if (!parameter.toLowerCase) {
  53278. continue;
  53279. }
  53280. var lowerCase = parameter.toLowerCase();
  53281. if (lowerCase !== evt.sourceEvent.key) {
  53282. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53283. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53284. if (actualkey !== lowerCase) {
  53285. continue;
  53286. }
  53287. }
  53288. }
  53289. }
  53290. }
  53291. action._executeCurrent(evt);
  53292. }
  53293. }
  53294. };
  53295. /** @hidden */
  53296. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53297. var properties = propertyPath.split(".");
  53298. for (var index = 0; index < properties.length - 1; index++) {
  53299. target = target[properties[index]];
  53300. }
  53301. return target;
  53302. };
  53303. /** @hidden */
  53304. ActionManager.prototype._getProperty = function (propertyPath) {
  53305. var properties = propertyPath.split(".");
  53306. return properties[properties.length - 1];
  53307. };
  53308. /**
  53309. * Serialize this manager to a JSON object
  53310. * @param name defines the property name to store this manager
  53311. * @returns a JSON representation of this manager
  53312. */
  53313. ActionManager.prototype.serialize = function (name) {
  53314. var root = {
  53315. children: new Array(),
  53316. name: name,
  53317. type: 3,
  53318. properties: new Array() // Empty for root but required
  53319. };
  53320. for (var i = 0; i < this.actions.length; i++) {
  53321. var triggerObject = {
  53322. type: 0,
  53323. children: new Array(),
  53324. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53325. properties: new Array()
  53326. };
  53327. var triggerOptions = this.actions[i].triggerOptions;
  53328. if (triggerOptions && typeof triggerOptions !== "number") {
  53329. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53330. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53331. }
  53332. else {
  53333. var parameter = {};
  53334. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53335. if (triggerOptions.parameter.mesh) {
  53336. parameter._meshId = triggerOptions.parameter.mesh.id;
  53337. }
  53338. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53339. }
  53340. }
  53341. // Serialize child action, recursively
  53342. this.actions[i].serialize(triggerObject);
  53343. // Add serialized trigger
  53344. root.children.push(triggerObject);
  53345. }
  53346. return root;
  53347. };
  53348. /**
  53349. * Creates a new ActionManager from a JSON data
  53350. * @param parsedActions defines the JSON data to read from
  53351. * @param object defines the hosting mesh
  53352. * @param scene defines the hosting scene
  53353. */
  53354. ActionManager.Parse = function (parsedActions, object, scene) {
  53355. var actionManager = new ActionManager(scene);
  53356. if (object === null)
  53357. scene.actionManager = actionManager;
  53358. else
  53359. object.actionManager = actionManager;
  53360. // instanciate a new object
  53361. var instanciate = function (name, params) {
  53362. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53363. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53364. newInstance.constructor.apply(newInstance, params);
  53365. return newInstance;
  53366. };
  53367. var parseParameter = function (name, value, target, propertyPath) {
  53368. if (propertyPath === null) {
  53369. // String, boolean or float
  53370. var floatValue = parseFloat(value);
  53371. if (value === "true" || value === "false")
  53372. return value === "true";
  53373. else
  53374. return isNaN(floatValue) ? value : floatValue;
  53375. }
  53376. var effectiveTarget = propertyPath.split(".");
  53377. var values = value.split(",");
  53378. // Get effective Target
  53379. for (var i = 0; i < effectiveTarget.length; i++) {
  53380. target = target[effectiveTarget[i]];
  53381. }
  53382. // Return appropriate value with its type
  53383. if (typeof (target) === "boolean")
  53384. return values[0] === "true";
  53385. if (typeof (target) === "string")
  53386. return values[0];
  53387. // Parameters with multiple values such as Vector3 etc.
  53388. var split = new Array();
  53389. for (var i = 0; i < values.length; i++)
  53390. split.push(parseFloat(values[i]));
  53391. if (target instanceof BABYLON.Vector3)
  53392. return BABYLON.Vector3.FromArray(split);
  53393. if (target instanceof BABYLON.Vector4)
  53394. return BABYLON.Vector4.FromArray(split);
  53395. if (target instanceof BABYLON.Color3)
  53396. return BABYLON.Color3.FromArray(split);
  53397. if (target instanceof BABYLON.Color4)
  53398. return BABYLON.Color4.FromArray(split);
  53399. return parseFloat(values[0]);
  53400. };
  53401. // traverse graph per trigger
  53402. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53403. if (combineArray === void 0) { combineArray = null; }
  53404. if (parsedAction.detached)
  53405. return;
  53406. var parameters = new Array();
  53407. var target = null;
  53408. var propertyPath = null;
  53409. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53410. // Parameters
  53411. if (parsedAction.type === 2)
  53412. parameters.push(actionManager);
  53413. else
  53414. parameters.push(trigger);
  53415. if (combine) {
  53416. var actions = new Array();
  53417. for (var j = 0; j < parsedAction.combine.length; j++) {
  53418. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53419. }
  53420. parameters.push(actions);
  53421. }
  53422. else {
  53423. for (var i = 0; i < parsedAction.properties.length; i++) {
  53424. var value = parsedAction.properties[i].value;
  53425. var name = parsedAction.properties[i].name;
  53426. var targetType = parsedAction.properties[i].targetType;
  53427. if (name === "target")
  53428. if (targetType !== null && targetType === "SceneProperties")
  53429. value = target = scene;
  53430. else
  53431. value = target = scene.getNodeByName(value);
  53432. else if (name === "parent")
  53433. value = scene.getNodeByName(value);
  53434. else if (name === "sound")
  53435. value = scene.getSoundByName(value);
  53436. else if (name !== "propertyPath") {
  53437. if (parsedAction.type === 2 && name === "operator")
  53438. value = BABYLON.ValueCondition[value];
  53439. else
  53440. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53441. }
  53442. else {
  53443. propertyPath = value;
  53444. }
  53445. parameters.push(value);
  53446. }
  53447. }
  53448. if (combineArray === null) {
  53449. parameters.push(condition);
  53450. }
  53451. else {
  53452. parameters.push(null);
  53453. }
  53454. // If interpolate value action
  53455. if (parsedAction.name === "InterpolateValueAction") {
  53456. var param = parameters[parameters.length - 2];
  53457. parameters[parameters.length - 1] = param;
  53458. parameters[parameters.length - 2] = condition;
  53459. }
  53460. // Action or condition(s) and not CombineAction
  53461. var newAction = instanciate(parsedAction.name, parameters);
  53462. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53463. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53464. if (action)
  53465. action.then(nothing);
  53466. else
  53467. actionManager.registerAction(nothing);
  53468. action = nothing;
  53469. }
  53470. if (combineArray === null) {
  53471. if (newAction instanceof BABYLON.Condition) {
  53472. condition = newAction;
  53473. newAction = action;
  53474. }
  53475. else {
  53476. condition = null;
  53477. if (action)
  53478. action.then(newAction);
  53479. else
  53480. actionManager.registerAction(newAction);
  53481. }
  53482. }
  53483. else {
  53484. combineArray.push(newAction);
  53485. }
  53486. for (var i = 0; i < parsedAction.children.length; i++)
  53487. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53488. };
  53489. // triggers
  53490. for (var i = 0; i < parsedActions.children.length; i++) {
  53491. var triggerParams;
  53492. var trigger = parsedActions.children[i];
  53493. if (trigger.properties.length > 0) {
  53494. var param = trigger.properties[0].value;
  53495. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53496. if (value._meshId) {
  53497. value.mesh = scene.getMeshByID(value._meshId);
  53498. }
  53499. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53500. }
  53501. else
  53502. triggerParams = ActionManager[trigger.name];
  53503. for (var j = 0; j < trigger.children.length; j++) {
  53504. if (!trigger.detached)
  53505. traverse(trigger.children[j], triggerParams, null, null);
  53506. }
  53507. }
  53508. };
  53509. /**
  53510. * Get a trigger name by index
  53511. * @param trigger defines the trigger index
  53512. * @returns a trigger name
  53513. */
  53514. ActionManager.GetTriggerName = function (trigger) {
  53515. switch (trigger) {
  53516. case 0: return "NothingTrigger";
  53517. case 1: return "OnPickTrigger";
  53518. case 2: return "OnLeftPickTrigger";
  53519. case 3: return "OnRightPickTrigger";
  53520. case 4: return "OnCenterPickTrigger";
  53521. case 5: return "OnPickDownTrigger";
  53522. case 6: return "OnPickUpTrigger";
  53523. case 7: return "OnLongPressTrigger";
  53524. case 8: return "OnPointerOverTrigger";
  53525. case 9: return "OnPointerOutTrigger";
  53526. case 10: return "OnEveryFrameTrigger";
  53527. case 11: return "OnIntersectionEnterTrigger";
  53528. case 12: return "OnIntersectionExitTrigger";
  53529. case 13: return "OnKeyDownTrigger";
  53530. case 14: return "OnKeyUpTrigger";
  53531. case 15: return "OnPickOutTrigger";
  53532. default: return "";
  53533. }
  53534. };
  53535. // Statics
  53536. ActionManager._NothingTrigger = 0;
  53537. ActionManager._OnPickTrigger = 1;
  53538. ActionManager._OnLeftPickTrigger = 2;
  53539. ActionManager._OnRightPickTrigger = 3;
  53540. ActionManager._OnCenterPickTrigger = 4;
  53541. ActionManager._OnPickDownTrigger = 5;
  53542. ActionManager._OnDoublePickTrigger = 6;
  53543. ActionManager._OnPickUpTrigger = 7;
  53544. ActionManager._OnLongPressTrigger = 8;
  53545. ActionManager._OnPointerOverTrigger = 9;
  53546. ActionManager._OnPointerOutTrigger = 10;
  53547. ActionManager._OnEveryFrameTrigger = 11;
  53548. ActionManager._OnIntersectionEnterTrigger = 12;
  53549. ActionManager._OnIntersectionExitTrigger = 13;
  53550. ActionManager._OnKeyDownTrigger = 14;
  53551. ActionManager._OnKeyUpTrigger = 15;
  53552. ActionManager._OnPickOutTrigger = 16;
  53553. /** Gets the list of active triggers */
  53554. ActionManager.Triggers = {};
  53555. return ActionManager;
  53556. }());
  53557. BABYLON.ActionManager = ActionManager;
  53558. })(BABYLON || (BABYLON = {}));
  53559. //# sourceMappingURL=babylon.actionManager.js.map
  53560. var BABYLON;
  53561. (function (BABYLON) {
  53562. var InterpolateValueAction = /** @class */ (function (_super) {
  53563. __extends(InterpolateValueAction, _super);
  53564. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53565. if (duration === void 0) { duration = 1000; }
  53566. var _this = _super.call(this, triggerOptions, condition) || this;
  53567. _this.propertyPath = propertyPath;
  53568. _this.value = value;
  53569. _this.duration = duration;
  53570. _this.stopOtherAnimations = stopOtherAnimations;
  53571. _this.onInterpolationDone = onInterpolationDone;
  53572. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53573. _this._target = _this._effectiveTarget = target;
  53574. return _this;
  53575. }
  53576. /** @hidden */
  53577. InterpolateValueAction.prototype._prepare = function () {
  53578. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53579. this._property = this._getProperty(this.propertyPath);
  53580. };
  53581. InterpolateValueAction.prototype.execute = function () {
  53582. var _this = this;
  53583. var scene = this._actionManager.getScene();
  53584. var keys = [
  53585. {
  53586. frame: 0,
  53587. value: this._effectiveTarget[this._property]
  53588. }, {
  53589. frame: 100,
  53590. value: this.value
  53591. }
  53592. ];
  53593. var dataType;
  53594. if (typeof this.value === "number") {
  53595. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53596. }
  53597. else if (this.value instanceof BABYLON.Color3) {
  53598. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53599. }
  53600. else if (this.value instanceof BABYLON.Vector3) {
  53601. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53602. }
  53603. else if (this.value instanceof BABYLON.Matrix) {
  53604. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53605. }
  53606. else if (this.value instanceof BABYLON.Quaternion) {
  53607. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53608. }
  53609. else {
  53610. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53611. return;
  53612. }
  53613. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53614. animation.setKeys(keys);
  53615. if (this.stopOtherAnimations) {
  53616. scene.stopAnimation(this._effectiveTarget);
  53617. }
  53618. var wrapper = function () {
  53619. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53620. if (_this.onInterpolationDone) {
  53621. _this.onInterpolationDone();
  53622. }
  53623. };
  53624. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53625. };
  53626. InterpolateValueAction.prototype.serialize = function (parent) {
  53627. return _super.prototype._serialize.call(this, {
  53628. name: "InterpolateValueAction",
  53629. properties: [
  53630. BABYLON.Action._GetTargetProperty(this._target),
  53631. { name: "propertyPath", value: this.propertyPath },
  53632. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53633. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53634. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53635. ]
  53636. }, parent);
  53637. };
  53638. return InterpolateValueAction;
  53639. }(BABYLON.Action));
  53640. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53641. })(BABYLON || (BABYLON = {}));
  53642. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53643. var BABYLON;
  53644. (function (BABYLON) {
  53645. var SwitchBooleanAction = /** @class */ (function (_super) {
  53646. __extends(SwitchBooleanAction, _super);
  53647. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53648. var _this = _super.call(this, triggerOptions, condition) || this;
  53649. _this.propertyPath = propertyPath;
  53650. _this._target = _this._effectiveTarget = target;
  53651. return _this;
  53652. }
  53653. /** @hidden */
  53654. SwitchBooleanAction.prototype._prepare = function () {
  53655. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53656. this._property = this._getProperty(this.propertyPath);
  53657. };
  53658. SwitchBooleanAction.prototype.execute = function () {
  53659. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53660. };
  53661. SwitchBooleanAction.prototype.serialize = function (parent) {
  53662. return _super.prototype._serialize.call(this, {
  53663. name: "SwitchBooleanAction",
  53664. properties: [
  53665. BABYLON.Action._GetTargetProperty(this._target),
  53666. { name: "propertyPath", value: this.propertyPath }
  53667. ]
  53668. }, parent);
  53669. };
  53670. return SwitchBooleanAction;
  53671. }(BABYLON.Action));
  53672. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53673. var SetStateAction = /** @class */ (function (_super) {
  53674. __extends(SetStateAction, _super);
  53675. function SetStateAction(triggerOptions, target, value, condition) {
  53676. var _this = _super.call(this, triggerOptions, condition) || this;
  53677. _this.value = value;
  53678. _this._target = target;
  53679. return _this;
  53680. }
  53681. SetStateAction.prototype.execute = function () {
  53682. this._target.state = this.value;
  53683. };
  53684. SetStateAction.prototype.serialize = function (parent) {
  53685. return _super.prototype._serialize.call(this, {
  53686. name: "SetStateAction",
  53687. properties: [
  53688. BABYLON.Action._GetTargetProperty(this._target),
  53689. { name: "value", value: this.value }
  53690. ]
  53691. }, parent);
  53692. };
  53693. return SetStateAction;
  53694. }(BABYLON.Action));
  53695. BABYLON.SetStateAction = SetStateAction;
  53696. var SetValueAction = /** @class */ (function (_super) {
  53697. __extends(SetValueAction, _super);
  53698. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53699. var _this = _super.call(this, triggerOptions, condition) || this;
  53700. _this.propertyPath = propertyPath;
  53701. _this.value = value;
  53702. _this._target = _this._effectiveTarget = target;
  53703. return _this;
  53704. }
  53705. /** @hidden */
  53706. SetValueAction.prototype._prepare = function () {
  53707. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53708. this._property = this._getProperty(this.propertyPath);
  53709. };
  53710. SetValueAction.prototype.execute = function () {
  53711. this._effectiveTarget[this._property] = this.value;
  53712. if (this._target.markAsDirty) {
  53713. this._target.markAsDirty(this._property);
  53714. }
  53715. };
  53716. SetValueAction.prototype.serialize = function (parent) {
  53717. return _super.prototype._serialize.call(this, {
  53718. name: "SetValueAction",
  53719. properties: [
  53720. BABYLON.Action._GetTargetProperty(this._target),
  53721. { name: "propertyPath", value: this.propertyPath },
  53722. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53723. ]
  53724. }, parent);
  53725. };
  53726. return SetValueAction;
  53727. }(BABYLON.Action));
  53728. BABYLON.SetValueAction = SetValueAction;
  53729. var IncrementValueAction = /** @class */ (function (_super) {
  53730. __extends(IncrementValueAction, _super);
  53731. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53732. var _this = _super.call(this, triggerOptions, condition) || this;
  53733. _this.propertyPath = propertyPath;
  53734. _this.value = value;
  53735. _this._target = _this._effectiveTarget = target;
  53736. return _this;
  53737. }
  53738. /** @hidden */
  53739. IncrementValueAction.prototype._prepare = function () {
  53740. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53741. this._property = this._getProperty(this.propertyPath);
  53742. if (typeof this._effectiveTarget[this._property] !== "number") {
  53743. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53744. }
  53745. };
  53746. IncrementValueAction.prototype.execute = function () {
  53747. this._effectiveTarget[this._property] += this.value;
  53748. if (this._target.markAsDirty) {
  53749. this._target.markAsDirty(this._property);
  53750. }
  53751. };
  53752. IncrementValueAction.prototype.serialize = function (parent) {
  53753. return _super.prototype._serialize.call(this, {
  53754. name: "IncrementValueAction",
  53755. properties: [
  53756. BABYLON.Action._GetTargetProperty(this._target),
  53757. { name: "propertyPath", value: this.propertyPath },
  53758. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53759. ]
  53760. }, parent);
  53761. };
  53762. return IncrementValueAction;
  53763. }(BABYLON.Action));
  53764. BABYLON.IncrementValueAction = IncrementValueAction;
  53765. var PlayAnimationAction = /** @class */ (function (_super) {
  53766. __extends(PlayAnimationAction, _super);
  53767. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53768. var _this = _super.call(this, triggerOptions, condition) || this;
  53769. _this.from = from;
  53770. _this.to = to;
  53771. _this.loop = loop;
  53772. _this._target = target;
  53773. return _this;
  53774. }
  53775. /** @hidden */
  53776. PlayAnimationAction.prototype._prepare = function () {
  53777. };
  53778. PlayAnimationAction.prototype.execute = function () {
  53779. var scene = this._actionManager.getScene();
  53780. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53781. };
  53782. PlayAnimationAction.prototype.serialize = function (parent) {
  53783. return _super.prototype._serialize.call(this, {
  53784. name: "PlayAnimationAction",
  53785. properties: [
  53786. BABYLON.Action._GetTargetProperty(this._target),
  53787. { name: "from", value: String(this.from) },
  53788. { name: "to", value: String(this.to) },
  53789. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53790. ]
  53791. }, parent);
  53792. };
  53793. return PlayAnimationAction;
  53794. }(BABYLON.Action));
  53795. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53796. var StopAnimationAction = /** @class */ (function (_super) {
  53797. __extends(StopAnimationAction, _super);
  53798. function StopAnimationAction(triggerOptions, target, condition) {
  53799. var _this = _super.call(this, triggerOptions, condition) || this;
  53800. _this._target = target;
  53801. return _this;
  53802. }
  53803. /** @hidden */
  53804. StopAnimationAction.prototype._prepare = function () {
  53805. };
  53806. StopAnimationAction.prototype.execute = function () {
  53807. var scene = this._actionManager.getScene();
  53808. scene.stopAnimation(this._target);
  53809. };
  53810. StopAnimationAction.prototype.serialize = function (parent) {
  53811. return _super.prototype._serialize.call(this, {
  53812. name: "StopAnimationAction",
  53813. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53814. }, parent);
  53815. };
  53816. return StopAnimationAction;
  53817. }(BABYLON.Action));
  53818. BABYLON.StopAnimationAction = StopAnimationAction;
  53819. var DoNothingAction = /** @class */ (function (_super) {
  53820. __extends(DoNothingAction, _super);
  53821. function DoNothingAction(triggerOptions, condition) {
  53822. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53823. return _super.call(this, triggerOptions, condition) || this;
  53824. }
  53825. DoNothingAction.prototype.execute = function () {
  53826. };
  53827. DoNothingAction.prototype.serialize = function (parent) {
  53828. return _super.prototype._serialize.call(this, {
  53829. name: "DoNothingAction",
  53830. properties: []
  53831. }, parent);
  53832. };
  53833. return DoNothingAction;
  53834. }(BABYLON.Action));
  53835. BABYLON.DoNothingAction = DoNothingAction;
  53836. var CombineAction = /** @class */ (function (_super) {
  53837. __extends(CombineAction, _super);
  53838. function CombineAction(triggerOptions, children, condition) {
  53839. var _this = _super.call(this, triggerOptions, condition) || this;
  53840. _this.children = children;
  53841. return _this;
  53842. }
  53843. /** @hidden */
  53844. CombineAction.prototype._prepare = function () {
  53845. for (var index = 0; index < this.children.length; index++) {
  53846. this.children[index]._actionManager = this._actionManager;
  53847. this.children[index]._prepare();
  53848. }
  53849. };
  53850. CombineAction.prototype.execute = function (evt) {
  53851. for (var index = 0; index < this.children.length; index++) {
  53852. this.children[index].execute(evt);
  53853. }
  53854. };
  53855. CombineAction.prototype.serialize = function (parent) {
  53856. var serializationObject = _super.prototype._serialize.call(this, {
  53857. name: "CombineAction",
  53858. properties: [],
  53859. combine: []
  53860. }, parent);
  53861. for (var i = 0; i < this.children.length; i++) {
  53862. serializationObject.combine.push(this.children[i].serialize(null));
  53863. }
  53864. return serializationObject;
  53865. };
  53866. return CombineAction;
  53867. }(BABYLON.Action));
  53868. BABYLON.CombineAction = CombineAction;
  53869. var ExecuteCodeAction = /** @class */ (function (_super) {
  53870. __extends(ExecuteCodeAction, _super);
  53871. function ExecuteCodeAction(triggerOptions, func, condition) {
  53872. var _this = _super.call(this, triggerOptions, condition) || this;
  53873. _this.func = func;
  53874. return _this;
  53875. }
  53876. ExecuteCodeAction.prototype.execute = function (evt) {
  53877. this.func(evt);
  53878. };
  53879. return ExecuteCodeAction;
  53880. }(BABYLON.Action));
  53881. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53882. var SetParentAction = /** @class */ (function (_super) {
  53883. __extends(SetParentAction, _super);
  53884. function SetParentAction(triggerOptions, target, parent, condition) {
  53885. var _this = _super.call(this, triggerOptions, condition) || this;
  53886. _this._target = target;
  53887. _this._parent = parent;
  53888. return _this;
  53889. }
  53890. /** @hidden */
  53891. SetParentAction.prototype._prepare = function () {
  53892. };
  53893. SetParentAction.prototype.execute = function () {
  53894. if (this._target.parent === this._parent) {
  53895. return;
  53896. }
  53897. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53898. invertParentWorldMatrix.invert();
  53899. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53900. this._target.parent = this._parent;
  53901. };
  53902. SetParentAction.prototype.serialize = function (parent) {
  53903. return _super.prototype._serialize.call(this, {
  53904. name: "SetParentAction",
  53905. properties: [
  53906. BABYLON.Action._GetTargetProperty(this._target),
  53907. BABYLON.Action._GetTargetProperty(this._parent),
  53908. ]
  53909. }, parent);
  53910. };
  53911. return SetParentAction;
  53912. }(BABYLON.Action));
  53913. BABYLON.SetParentAction = SetParentAction;
  53914. var PlaySoundAction = /** @class */ (function (_super) {
  53915. __extends(PlaySoundAction, _super);
  53916. function PlaySoundAction(triggerOptions, sound, condition) {
  53917. var _this = _super.call(this, triggerOptions, condition) || this;
  53918. _this._sound = sound;
  53919. return _this;
  53920. }
  53921. /** @hidden */
  53922. PlaySoundAction.prototype._prepare = function () {
  53923. };
  53924. PlaySoundAction.prototype.execute = function () {
  53925. if (this._sound !== undefined)
  53926. this._sound.play();
  53927. };
  53928. PlaySoundAction.prototype.serialize = function (parent) {
  53929. return _super.prototype._serialize.call(this, {
  53930. name: "PlaySoundAction",
  53931. properties: [{ name: "sound", value: this._sound.name }]
  53932. }, parent);
  53933. };
  53934. return PlaySoundAction;
  53935. }(BABYLON.Action));
  53936. BABYLON.PlaySoundAction = PlaySoundAction;
  53937. var StopSoundAction = /** @class */ (function (_super) {
  53938. __extends(StopSoundAction, _super);
  53939. function StopSoundAction(triggerOptions, sound, condition) {
  53940. var _this = _super.call(this, triggerOptions, condition) || this;
  53941. _this._sound = sound;
  53942. return _this;
  53943. }
  53944. /** @hidden */
  53945. StopSoundAction.prototype._prepare = function () {
  53946. };
  53947. StopSoundAction.prototype.execute = function () {
  53948. if (this._sound !== undefined)
  53949. this._sound.stop();
  53950. };
  53951. StopSoundAction.prototype.serialize = function (parent) {
  53952. return _super.prototype._serialize.call(this, {
  53953. name: "StopSoundAction",
  53954. properties: [{ name: "sound", value: this._sound.name }]
  53955. }, parent);
  53956. };
  53957. return StopSoundAction;
  53958. }(BABYLON.Action));
  53959. BABYLON.StopSoundAction = StopSoundAction;
  53960. })(BABYLON || (BABYLON = {}));
  53961. //# sourceMappingURL=babylon.directActions.js.map
  53962. var BABYLON;
  53963. (function (BABYLON) {
  53964. var SpriteManager = /** @class */ (function () {
  53965. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53966. if (epsilon === void 0) { epsilon = 0.01; }
  53967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53968. this.name = name;
  53969. this.sprites = new Array();
  53970. this.renderingGroupId = 0;
  53971. this.layerMask = 0x0FFFFFFF;
  53972. this.fogEnabled = true;
  53973. this.isPickable = false;
  53974. /**
  53975. * An event triggered when the manager is disposed.
  53976. */
  53977. this.onDisposeObservable = new BABYLON.Observable();
  53978. this._vertexBuffers = {};
  53979. this._capacity = capacity;
  53980. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53981. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53982. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53983. if (cellSize.width && cellSize.height) {
  53984. this.cellWidth = cellSize.width;
  53985. this.cellHeight = cellSize.height;
  53986. }
  53987. else if (cellSize !== undefined) {
  53988. this.cellWidth = cellSize;
  53989. this.cellHeight = cellSize;
  53990. }
  53991. else {
  53992. return;
  53993. }
  53994. this._epsilon = epsilon;
  53995. this._scene = scene;
  53996. this._scene.spriteManagers.push(this);
  53997. var indices = [];
  53998. var index = 0;
  53999. for (var count = 0; count < capacity; count++) {
  54000. indices.push(index);
  54001. indices.push(index + 1);
  54002. indices.push(index + 2);
  54003. indices.push(index);
  54004. indices.push(index + 2);
  54005. indices.push(index + 3);
  54006. index += 4;
  54007. }
  54008. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54009. // VBO
  54010. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54011. this._vertexData = new Float32Array(capacity * 16 * 4);
  54012. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54013. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54014. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54015. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54016. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54017. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54018. this._vertexBuffers["options"] = options;
  54019. this._vertexBuffers["cellInfo"] = cellInfo;
  54020. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54021. // Effects
  54022. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54023. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54024. }
  54025. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54026. set: function (callback) {
  54027. if (this._onDisposeObserver) {
  54028. this.onDisposeObservable.remove(this._onDisposeObserver);
  54029. }
  54030. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. Object.defineProperty(SpriteManager.prototype, "texture", {
  54036. get: function () {
  54037. return this._spriteTexture;
  54038. },
  54039. set: function (value) {
  54040. this._spriteTexture = value;
  54041. },
  54042. enumerable: true,
  54043. configurable: true
  54044. });
  54045. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54046. var arrayOffset = index * 16;
  54047. if (offsetX === 0)
  54048. offsetX = this._epsilon;
  54049. else if (offsetX === 1)
  54050. offsetX = 1 - this._epsilon;
  54051. if (offsetY === 0)
  54052. offsetY = this._epsilon;
  54053. else if (offsetY === 1)
  54054. offsetY = 1 - this._epsilon;
  54055. this._vertexData[arrayOffset] = sprite.position.x;
  54056. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54057. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54058. this._vertexData[arrayOffset + 3] = sprite.angle;
  54059. this._vertexData[arrayOffset + 4] = sprite.width;
  54060. this._vertexData[arrayOffset + 5] = sprite.height;
  54061. this._vertexData[arrayOffset + 6] = offsetX;
  54062. this._vertexData[arrayOffset + 7] = offsetY;
  54063. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54064. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54065. var offset = (sprite.cellIndex / rowSize) >> 0;
  54066. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54067. this._vertexData[arrayOffset + 11] = offset;
  54068. // Color
  54069. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54070. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54071. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54072. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54073. };
  54074. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54075. var count = Math.min(this._capacity, this.sprites.length);
  54076. var min = BABYLON.Vector3.Zero();
  54077. var max = BABYLON.Vector3.Zero();
  54078. var distance = Number.MAX_VALUE;
  54079. var currentSprite = null;
  54080. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54081. var cameraView = camera.getViewMatrix();
  54082. for (var index = 0; index < count; index++) {
  54083. var sprite = this.sprites[index];
  54084. if (!sprite) {
  54085. continue;
  54086. }
  54087. if (predicate) {
  54088. if (!predicate(sprite)) {
  54089. continue;
  54090. }
  54091. }
  54092. else if (!sprite.isPickable) {
  54093. continue;
  54094. }
  54095. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54096. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54097. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54098. if (ray.intersectsBoxMinMax(min, max)) {
  54099. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54100. if (distance > currentDistance) {
  54101. distance = currentDistance;
  54102. currentSprite = sprite;
  54103. if (fastCheck) {
  54104. break;
  54105. }
  54106. }
  54107. }
  54108. }
  54109. if (currentSprite) {
  54110. var result = new BABYLON.PickingInfo();
  54111. result.hit = true;
  54112. result.pickedSprite = currentSprite;
  54113. result.distance = distance;
  54114. return result;
  54115. }
  54116. return null;
  54117. };
  54118. SpriteManager.prototype.render = function () {
  54119. // Check
  54120. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54121. return;
  54122. var engine = this._scene.getEngine();
  54123. var baseSize = this._spriteTexture.getBaseSize();
  54124. // Sprites
  54125. var deltaTime = engine.getDeltaTime();
  54126. var max = Math.min(this._capacity, this.sprites.length);
  54127. var rowSize = baseSize.width / this.cellWidth;
  54128. var offset = 0;
  54129. for (var index = 0; index < max; index++) {
  54130. var sprite = this.sprites[index];
  54131. if (!sprite || !sprite.isVisible) {
  54132. continue;
  54133. }
  54134. sprite._animate(deltaTime);
  54135. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54136. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54137. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54138. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54139. }
  54140. this._buffer.update(this._vertexData);
  54141. // Render
  54142. var effect = this._effectBase;
  54143. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54144. effect = this._effectFog;
  54145. }
  54146. engine.enableEffect(effect);
  54147. var viewMatrix = this._scene.getViewMatrix();
  54148. effect.setTexture("diffuseSampler", this._spriteTexture);
  54149. effect.setMatrix("view", viewMatrix);
  54150. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54151. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54152. // Fog
  54153. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54154. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54155. effect.setColor3("vFogColor", this._scene.fogColor);
  54156. }
  54157. // VBOs
  54158. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54159. // Draw order
  54160. engine.setDepthFunctionToLessOrEqual();
  54161. effect.setBool("alphaTest", true);
  54162. engine.setColorWrite(false);
  54163. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54164. engine.setColorWrite(true);
  54165. effect.setBool("alphaTest", false);
  54166. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54167. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54168. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54169. };
  54170. SpriteManager.prototype.dispose = function () {
  54171. if (this._buffer) {
  54172. this._buffer.dispose();
  54173. this._buffer = null;
  54174. }
  54175. if (this._indexBuffer) {
  54176. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54177. this._indexBuffer = null;
  54178. }
  54179. if (this._spriteTexture) {
  54180. this._spriteTexture.dispose();
  54181. this._spriteTexture = null;
  54182. }
  54183. // Remove from scene
  54184. var index = this._scene.spriteManagers.indexOf(this);
  54185. this._scene.spriteManagers.splice(index, 1);
  54186. // Callback
  54187. this.onDisposeObservable.notifyObservers(this);
  54188. this.onDisposeObservable.clear();
  54189. };
  54190. return SpriteManager;
  54191. }());
  54192. BABYLON.SpriteManager = SpriteManager;
  54193. })(BABYLON || (BABYLON = {}));
  54194. //# sourceMappingURL=babylon.spriteManager.js.map
  54195. var BABYLON;
  54196. (function (BABYLON) {
  54197. var Sprite = /** @class */ (function () {
  54198. function Sprite(name, manager) {
  54199. this.name = name;
  54200. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54201. this.width = 1.0;
  54202. this.height = 1.0;
  54203. this.angle = 0;
  54204. this.cellIndex = 0;
  54205. this.invertU = 0;
  54206. this.invertV = 0;
  54207. this.animations = new Array();
  54208. this.isPickable = false;
  54209. this._animationStarted = false;
  54210. this._loopAnimation = false;
  54211. this._fromIndex = 0;
  54212. this._toIndex = 0;
  54213. this._delay = 0;
  54214. this._direction = 1;
  54215. this._time = 0;
  54216. /**
  54217. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54218. */
  54219. this.isVisible = true;
  54220. this._manager = manager;
  54221. this._manager.sprites.push(this);
  54222. this.position = BABYLON.Vector3.Zero();
  54223. }
  54224. Object.defineProperty(Sprite.prototype, "size", {
  54225. get: function () {
  54226. return this.width;
  54227. },
  54228. set: function (value) {
  54229. this.width = value;
  54230. this.height = value;
  54231. },
  54232. enumerable: true,
  54233. configurable: true
  54234. });
  54235. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54236. this._fromIndex = from;
  54237. this._toIndex = to;
  54238. this._loopAnimation = loop;
  54239. this._delay = delay;
  54240. this._animationStarted = true;
  54241. this._direction = from < to ? 1 : -1;
  54242. this.cellIndex = from;
  54243. this._time = 0;
  54244. this._onAnimationEnd = onAnimationEnd;
  54245. };
  54246. Sprite.prototype.stopAnimation = function () {
  54247. this._animationStarted = false;
  54248. };
  54249. /** @hidden */
  54250. Sprite.prototype._animate = function (deltaTime) {
  54251. if (!this._animationStarted)
  54252. return;
  54253. this._time += deltaTime;
  54254. if (this._time > this._delay) {
  54255. this._time = this._time % this._delay;
  54256. this.cellIndex += this._direction;
  54257. if (this.cellIndex > this._toIndex) {
  54258. if (this._loopAnimation) {
  54259. this.cellIndex = this._fromIndex;
  54260. }
  54261. else {
  54262. this.cellIndex = this._toIndex;
  54263. this._animationStarted = false;
  54264. if (this._onAnimationEnd) {
  54265. this._onAnimationEnd();
  54266. }
  54267. if (this.disposeWhenFinishedAnimating) {
  54268. this.dispose();
  54269. }
  54270. }
  54271. }
  54272. }
  54273. };
  54274. Sprite.prototype.dispose = function () {
  54275. for (var i = 0; i < this._manager.sprites.length; i++) {
  54276. if (this._manager.sprites[i] == this) {
  54277. this._manager.sprites.splice(i, 1);
  54278. }
  54279. }
  54280. };
  54281. return Sprite;
  54282. }());
  54283. BABYLON.Sprite = Sprite;
  54284. })(BABYLON || (BABYLON = {}));
  54285. //# sourceMappingURL=babylon.sprite.js.map
  54286. var BABYLON;
  54287. (function (BABYLON) {
  54288. var IntersectionInfo = /** @class */ (function () {
  54289. function IntersectionInfo(bu, bv, distance) {
  54290. this.bu = bu;
  54291. this.bv = bv;
  54292. this.distance = distance;
  54293. this.faceId = 0;
  54294. this.subMeshId = 0;
  54295. }
  54296. return IntersectionInfo;
  54297. }());
  54298. BABYLON.IntersectionInfo = IntersectionInfo;
  54299. /**
  54300. * Information about the result of picking within a scene
  54301. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54302. */
  54303. var PickingInfo = /** @class */ (function () {
  54304. function PickingInfo() {
  54305. /**
  54306. * If the pick collided with an object
  54307. */
  54308. this.hit = false;
  54309. /**
  54310. * Distance away where the pick collided
  54311. */
  54312. this.distance = 0;
  54313. /**
  54314. * The location of pick collision
  54315. */
  54316. this.pickedPoint = null;
  54317. /**
  54318. * The mesh corresponding the the pick collision
  54319. */
  54320. this.pickedMesh = null;
  54321. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54322. this.bu = 0;
  54323. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54324. this.bv = 0;
  54325. /** The id of the face on the mesh that was picked */
  54326. this.faceId = -1;
  54327. /** Id of the the submesh that was picked */
  54328. this.subMeshId = 0;
  54329. /** If a sprite was picked, this will be the sprite the pick collided with */
  54330. this.pickedSprite = null;
  54331. /**
  54332. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54333. */
  54334. this.originMesh = null;
  54335. /**
  54336. * The ray that was used to perform the picking.
  54337. */
  54338. this.ray = null;
  54339. }
  54340. /**
  54341. * Gets the normal correspodning to the face the pick collided with
  54342. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54343. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54344. * @returns The normal correspodning to the face the pick collided with
  54345. */
  54346. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54347. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54348. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54349. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54350. return null;
  54351. }
  54352. var indices = this.pickedMesh.getIndices();
  54353. if (!indices) {
  54354. return null;
  54355. }
  54356. var result;
  54357. if (useVerticesNormals) {
  54358. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54359. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54360. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54361. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54362. normal0 = normal0.scale(this.bu);
  54363. normal1 = normal1.scale(this.bv);
  54364. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54365. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54366. }
  54367. else {
  54368. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54369. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54370. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54371. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54372. var p1p2 = vertex1.subtract(vertex2);
  54373. var p3p2 = vertex3.subtract(vertex2);
  54374. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54375. }
  54376. if (useWorldCoordinates) {
  54377. var wm = this.pickedMesh.getWorldMatrix();
  54378. if (this.pickedMesh.nonUniformScaling) {
  54379. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54380. wm = BABYLON.Tmp.Matrix[0];
  54381. wm.setTranslationFromFloats(0, 0, 0);
  54382. wm.invert();
  54383. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54384. wm = BABYLON.Tmp.Matrix[1];
  54385. }
  54386. result = BABYLON.Vector3.TransformNormal(result, wm);
  54387. }
  54388. result.normalize();
  54389. return result;
  54390. };
  54391. /**
  54392. * Gets the texture coordinates of where the pick occured
  54393. * @returns the vector containing the coordnates of the texture
  54394. */
  54395. PickingInfo.prototype.getTextureCoordinates = function () {
  54396. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54397. return null;
  54398. }
  54399. var indices = this.pickedMesh.getIndices();
  54400. if (!indices) {
  54401. return null;
  54402. }
  54403. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54404. if (!uvs) {
  54405. return null;
  54406. }
  54407. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54408. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54409. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54410. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54411. uv1 = uv1.scale(this.bu);
  54412. uv2 = uv2.scale(this.bv);
  54413. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54414. };
  54415. return PickingInfo;
  54416. }());
  54417. BABYLON.PickingInfo = PickingInfo;
  54418. })(BABYLON || (BABYLON = {}));
  54419. //# sourceMappingURL=babylon.pickingInfo.js.map
  54420. var BABYLON;
  54421. (function (BABYLON) {
  54422. var Ray = /** @class */ (function () {
  54423. function Ray(origin, direction, length) {
  54424. if (length === void 0) { length = Number.MAX_VALUE; }
  54425. this.origin = origin;
  54426. this.direction = direction;
  54427. this.length = length;
  54428. }
  54429. // Methods
  54430. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54431. var d = 0.0;
  54432. var maxValue = Number.MAX_VALUE;
  54433. var inv;
  54434. var min;
  54435. var max;
  54436. var temp;
  54437. if (Math.abs(this.direction.x) < 0.0000001) {
  54438. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54439. return false;
  54440. }
  54441. }
  54442. else {
  54443. inv = 1.0 / this.direction.x;
  54444. min = (minimum.x - this.origin.x) * inv;
  54445. max = (maximum.x - this.origin.x) * inv;
  54446. if (max === -Infinity) {
  54447. max = Infinity;
  54448. }
  54449. if (min > max) {
  54450. temp = min;
  54451. min = max;
  54452. max = temp;
  54453. }
  54454. d = Math.max(min, d);
  54455. maxValue = Math.min(max, maxValue);
  54456. if (d > maxValue) {
  54457. return false;
  54458. }
  54459. }
  54460. if (Math.abs(this.direction.y) < 0.0000001) {
  54461. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54462. return false;
  54463. }
  54464. }
  54465. else {
  54466. inv = 1.0 / this.direction.y;
  54467. min = (minimum.y - this.origin.y) * inv;
  54468. max = (maximum.y - this.origin.y) * inv;
  54469. if (max === -Infinity) {
  54470. max = Infinity;
  54471. }
  54472. if (min > max) {
  54473. temp = min;
  54474. min = max;
  54475. max = temp;
  54476. }
  54477. d = Math.max(min, d);
  54478. maxValue = Math.min(max, maxValue);
  54479. if (d > maxValue) {
  54480. return false;
  54481. }
  54482. }
  54483. if (Math.abs(this.direction.z) < 0.0000001) {
  54484. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54485. return false;
  54486. }
  54487. }
  54488. else {
  54489. inv = 1.0 / this.direction.z;
  54490. min = (minimum.z - this.origin.z) * inv;
  54491. max = (maximum.z - this.origin.z) * inv;
  54492. if (max === -Infinity) {
  54493. max = Infinity;
  54494. }
  54495. if (min > max) {
  54496. temp = min;
  54497. min = max;
  54498. max = temp;
  54499. }
  54500. d = Math.max(min, d);
  54501. maxValue = Math.min(max, maxValue);
  54502. if (d > maxValue) {
  54503. return false;
  54504. }
  54505. }
  54506. return true;
  54507. };
  54508. Ray.prototype.intersectsBox = function (box) {
  54509. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54510. };
  54511. Ray.prototype.intersectsSphere = function (sphere) {
  54512. var x = sphere.center.x - this.origin.x;
  54513. var y = sphere.center.y - this.origin.y;
  54514. var z = sphere.center.z - this.origin.z;
  54515. var pyth = (x * x) + (y * y) + (z * z);
  54516. var rr = sphere.radius * sphere.radius;
  54517. if (pyth <= rr) {
  54518. return true;
  54519. }
  54520. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54521. if (dot < 0.0) {
  54522. return false;
  54523. }
  54524. var temp = pyth - (dot * dot);
  54525. return temp <= rr;
  54526. };
  54527. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54528. if (!this._edge1) {
  54529. this._edge1 = BABYLON.Vector3.Zero();
  54530. this._edge2 = BABYLON.Vector3.Zero();
  54531. this._pvec = BABYLON.Vector3.Zero();
  54532. this._tvec = BABYLON.Vector3.Zero();
  54533. this._qvec = BABYLON.Vector3.Zero();
  54534. }
  54535. vertex1.subtractToRef(vertex0, this._edge1);
  54536. vertex2.subtractToRef(vertex0, this._edge2);
  54537. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54538. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54539. if (det === 0) {
  54540. return null;
  54541. }
  54542. var invdet = 1 / det;
  54543. this.origin.subtractToRef(vertex0, this._tvec);
  54544. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54545. if (bu < 0 || bu > 1.0) {
  54546. return null;
  54547. }
  54548. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54549. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54550. if (bv < 0 || bu + bv > 1.0) {
  54551. return null;
  54552. }
  54553. //check if the distance is longer than the predefined length.
  54554. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54555. if (distance > this.length) {
  54556. return null;
  54557. }
  54558. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54559. };
  54560. Ray.prototype.intersectsPlane = function (plane) {
  54561. var distance;
  54562. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54563. if (Math.abs(result1) < 9.99999997475243E-07) {
  54564. return null;
  54565. }
  54566. else {
  54567. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54568. distance = (-plane.d - result2) / result1;
  54569. if (distance < 0.0) {
  54570. if (distance < -9.99999997475243E-07) {
  54571. return null;
  54572. }
  54573. else {
  54574. return 0;
  54575. }
  54576. }
  54577. return distance;
  54578. }
  54579. };
  54580. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54581. var tm = BABYLON.Tmp.Matrix[0];
  54582. mesh.getWorldMatrix().invertToRef(tm);
  54583. if (this._tmpRay) {
  54584. Ray.TransformToRef(this, tm, this._tmpRay);
  54585. }
  54586. else {
  54587. this._tmpRay = Ray.Transform(this, tm);
  54588. }
  54589. return mesh.intersects(this._tmpRay, fastCheck);
  54590. };
  54591. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54592. if (results) {
  54593. results.length = 0;
  54594. }
  54595. else {
  54596. results = [];
  54597. }
  54598. for (var i = 0; i < meshes.length; i++) {
  54599. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54600. if (pickInfo.hit) {
  54601. results.push(pickInfo);
  54602. }
  54603. }
  54604. results.sort(this._comparePickingInfo);
  54605. return results;
  54606. };
  54607. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54608. if (pickingInfoA.distance < pickingInfoB.distance) {
  54609. return -1;
  54610. }
  54611. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54612. return 1;
  54613. }
  54614. else {
  54615. return 0;
  54616. }
  54617. };
  54618. /**
  54619. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54620. * @param sega the first point of the segment to test the intersection against
  54621. * @param segb the second point of the segment to test the intersection against
  54622. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54623. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54624. */
  54625. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54626. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54627. var u = segb.subtract(sega);
  54628. var v = rsegb.subtract(this.origin);
  54629. var w = sega.subtract(this.origin);
  54630. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54631. var b = BABYLON.Vector3.Dot(u, v);
  54632. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54633. var d = BABYLON.Vector3.Dot(u, w);
  54634. var e = BABYLON.Vector3.Dot(v, w);
  54635. var D = a * c - b * b; // always >= 0
  54636. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54637. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54638. // compute the line parameters of the two closest points
  54639. if (D < Ray.smallnum) { // the lines are almost parallel
  54640. sN = 0.0; // force using point P0 on segment S1
  54641. sD = 1.0; // to prevent possible division by 0.0 later
  54642. tN = e;
  54643. tD = c;
  54644. }
  54645. else { // get the closest points on the infinite lines
  54646. sN = (b * e - c * d);
  54647. tN = (a * e - b * d);
  54648. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54649. sN = 0.0;
  54650. tN = e;
  54651. tD = c;
  54652. }
  54653. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54654. sN = sD;
  54655. tN = e + b;
  54656. tD = c;
  54657. }
  54658. }
  54659. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54660. tN = 0.0;
  54661. // recompute sc for this edge
  54662. if (-d < 0.0) {
  54663. sN = 0.0;
  54664. }
  54665. else if (-d > a)
  54666. sN = sD;
  54667. else {
  54668. sN = -d;
  54669. sD = a;
  54670. }
  54671. }
  54672. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54673. tN = tD;
  54674. // recompute sc for this edge
  54675. if ((-d + b) < 0.0) {
  54676. sN = 0;
  54677. }
  54678. else if ((-d + b) > a) {
  54679. sN = sD;
  54680. }
  54681. else {
  54682. sN = (-d + b);
  54683. sD = a;
  54684. }
  54685. }
  54686. // finally do the division to get sc and tc
  54687. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54688. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54689. // get the difference of the two closest points
  54690. var qtc = v.multiplyByFloats(tc, tc, tc);
  54691. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54692. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54693. if (isIntersected) {
  54694. return qtc.length();
  54695. }
  54696. return -1;
  54697. };
  54698. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54699. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54700. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54701. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54702. this.direction.normalize();
  54703. return this;
  54704. };
  54705. // Statics
  54706. Ray.Zero = function () {
  54707. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54708. };
  54709. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54710. var result = Ray.Zero();
  54711. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54712. };
  54713. /**
  54714. * 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
  54715. * transformed to the given world matrix.
  54716. * @param origin The origin point
  54717. * @param end The end point
  54718. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54719. */
  54720. Ray.CreateNewFromTo = function (origin, end, world) {
  54721. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54722. var direction = end.subtract(origin);
  54723. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54724. direction.normalize();
  54725. return Ray.Transform(new Ray(origin, direction, length), world);
  54726. };
  54727. Ray.Transform = function (ray, matrix) {
  54728. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54729. Ray.TransformToRef(ray, matrix, result);
  54730. return result;
  54731. };
  54732. Ray.TransformToRef = function (ray, matrix, result) {
  54733. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54734. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54735. result.length = ray.length;
  54736. var dir = result.direction;
  54737. var len = dir.length();
  54738. if (!(len === 0 || len === 1)) {
  54739. var num = 1.0 / len;
  54740. dir.x *= num;
  54741. dir.y *= num;
  54742. dir.z *= num;
  54743. result.length *= len;
  54744. }
  54745. };
  54746. Ray.smallnum = 0.00000001;
  54747. Ray.rayl = 10e8;
  54748. return Ray;
  54749. }());
  54750. BABYLON.Ray = Ray;
  54751. })(BABYLON || (BABYLON = {}));
  54752. //# sourceMappingURL=babylon.ray.js.map
  54753. var BABYLON;
  54754. (function (BABYLON) {
  54755. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54756. if (boxMin.x > sphereCenter.x + sphereRadius)
  54757. return false;
  54758. if (sphereCenter.x - sphereRadius > boxMax.x)
  54759. return false;
  54760. if (boxMin.y > sphereCenter.y + sphereRadius)
  54761. return false;
  54762. if (sphereCenter.y - sphereRadius > boxMax.y)
  54763. return false;
  54764. if (boxMin.z > sphereCenter.z + sphereRadius)
  54765. return false;
  54766. if (sphereCenter.z - sphereRadius > boxMax.z)
  54767. return false;
  54768. return true;
  54769. };
  54770. var getLowestRoot = (function () {
  54771. var result = { root: 0, found: false };
  54772. return function (a, b, c, maxR) {
  54773. result.root = 0;
  54774. result.found = false;
  54775. var determinant = b * b - 4.0 * a * c;
  54776. if (determinant < 0)
  54777. return result;
  54778. var sqrtD = Math.sqrt(determinant);
  54779. var r1 = (-b - sqrtD) / (2.0 * a);
  54780. var r2 = (-b + sqrtD) / (2.0 * a);
  54781. if (r1 > r2) {
  54782. var temp = r2;
  54783. r2 = r1;
  54784. r1 = temp;
  54785. }
  54786. if (r1 > 0 && r1 < maxR) {
  54787. result.root = r1;
  54788. result.found = true;
  54789. return result;
  54790. }
  54791. if (r2 > 0 && r2 < maxR) {
  54792. result.root = r2;
  54793. result.found = true;
  54794. return result;
  54795. }
  54796. return result;
  54797. };
  54798. })();
  54799. var Collider = /** @class */ (function () {
  54800. function Collider() {
  54801. this._collisionPoint = BABYLON.Vector3.Zero();
  54802. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54803. this._tempVector = BABYLON.Vector3.Zero();
  54804. this._tempVector2 = BABYLON.Vector3.Zero();
  54805. this._tempVector3 = BABYLON.Vector3.Zero();
  54806. this._tempVector4 = BABYLON.Vector3.Zero();
  54807. this._edge = BABYLON.Vector3.Zero();
  54808. this._baseToVertex = BABYLON.Vector3.Zero();
  54809. this._destinationPoint = BABYLON.Vector3.Zero();
  54810. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54811. this._displacementVector = BABYLON.Vector3.Zero();
  54812. /** @hidden */
  54813. this._radius = BABYLON.Vector3.One();
  54814. /** @hidden */
  54815. this._retry = 0;
  54816. /** @hidden */
  54817. this._basePointWorld = BABYLON.Vector3.Zero();
  54818. this._velocityWorld = BABYLON.Vector3.Zero();
  54819. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54820. this._collisionMask = -1;
  54821. }
  54822. Object.defineProperty(Collider.prototype, "collisionMask", {
  54823. get: function () {
  54824. return this._collisionMask;
  54825. },
  54826. set: function (mask) {
  54827. this._collisionMask = !isNaN(mask) ? mask : -1;
  54828. },
  54829. enumerable: true,
  54830. configurable: true
  54831. });
  54832. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54833. /**
  54834. * Gets the plane normal used to compute the sliding response (in local space)
  54835. */
  54836. get: function () {
  54837. return this._slidePlaneNormal;
  54838. },
  54839. enumerable: true,
  54840. configurable: true
  54841. });
  54842. // Methods
  54843. /** @hidden */
  54844. Collider.prototype._initialize = function (source, dir, e) {
  54845. this._velocity = dir;
  54846. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54847. this._basePoint = source;
  54848. source.multiplyToRef(this._radius, this._basePointWorld);
  54849. dir.multiplyToRef(this._radius, this._velocityWorld);
  54850. this._velocityWorldLength = this._velocityWorld.length();
  54851. this._epsilon = e;
  54852. this.collisionFound = false;
  54853. };
  54854. /** @hidden */
  54855. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54856. pa.subtractToRef(point, this._tempVector);
  54857. pb.subtractToRef(point, this._tempVector2);
  54858. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54859. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54860. if (d < 0)
  54861. return false;
  54862. pc.subtractToRef(point, this._tempVector3);
  54863. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54864. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54865. if (d < 0)
  54866. return false;
  54867. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54868. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54869. return d >= 0;
  54870. };
  54871. /** @hidden */
  54872. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54873. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54874. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54875. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54876. return false;
  54877. }
  54878. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54879. return false;
  54880. return true;
  54881. };
  54882. /** @hidden */
  54883. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54884. var t0;
  54885. var embeddedInPlane = false;
  54886. //defensive programming, actually not needed.
  54887. if (!trianglePlaneArray) {
  54888. trianglePlaneArray = [];
  54889. }
  54890. if (!trianglePlaneArray[faceIndex]) {
  54891. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54892. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54893. }
  54894. var trianglePlane = trianglePlaneArray[faceIndex];
  54895. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54896. return;
  54897. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54898. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54899. if (normalDotVelocity == 0) {
  54900. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54901. return;
  54902. embeddedInPlane = true;
  54903. t0 = 0;
  54904. }
  54905. else {
  54906. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54907. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54908. if (t0 > t1) {
  54909. var temp = t1;
  54910. t1 = t0;
  54911. t0 = temp;
  54912. }
  54913. if (t0 > 1.0 || t1 < 0.0)
  54914. return;
  54915. if (t0 < 0)
  54916. t0 = 0;
  54917. if (t0 > 1.0)
  54918. t0 = 1.0;
  54919. }
  54920. this._collisionPoint.copyFromFloats(0, 0, 0);
  54921. var found = false;
  54922. var t = 1.0;
  54923. if (!embeddedInPlane) {
  54924. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54925. this._velocity.scaleToRef(t0, this._tempVector);
  54926. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54927. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54928. found = true;
  54929. t = t0;
  54930. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54931. }
  54932. }
  54933. if (!found) {
  54934. var velocitySquaredLength = this._velocity.lengthSquared();
  54935. var a = velocitySquaredLength;
  54936. this._basePoint.subtractToRef(p1, this._tempVector);
  54937. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54938. var c = this._tempVector.lengthSquared() - 1.0;
  54939. var lowestRoot = getLowestRoot(a, b, c, t);
  54940. if (lowestRoot.found) {
  54941. t = lowestRoot.root;
  54942. found = true;
  54943. this._collisionPoint.copyFrom(p1);
  54944. }
  54945. this._basePoint.subtractToRef(p2, this._tempVector);
  54946. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54947. c = this._tempVector.lengthSquared() - 1.0;
  54948. lowestRoot = getLowestRoot(a, b, c, t);
  54949. if (lowestRoot.found) {
  54950. t = lowestRoot.root;
  54951. found = true;
  54952. this._collisionPoint.copyFrom(p2);
  54953. }
  54954. this._basePoint.subtractToRef(p3, this._tempVector);
  54955. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54956. c = this._tempVector.lengthSquared() - 1.0;
  54957. lowestRoot = getLowestRoot(a, b, c, t);
  54958. if (lowestRoot.found) {
  54959. t = lowestRoot.root;
  54960. found = true;
  54961. this._collisionPoint.copyFrom(p3);
  54962. }
  54963. p2.subtractToRef(p1, this._edge);
  54964. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54965. var edgeSquaredLength = this._edge.lengthSquared();
  54966. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54967. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54968. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54969. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54970. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54971. lowestRoot = getLowestRoot(a, b, c, t);
  54972. if (lowestRoot.found) {
  54973. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54974. if (f >= 0.0 && f <= 1.0) {
  54975. t = lowestRoot.root;
  54976. found = true;
  54977. this._edge.scaleInPlace(f);
  54978. p1.addToRef(this._edge, this._collisionPoint);
  54979. }
  54980. }
  54981. p3.subtractToRef(p2, this._edge);
  54982. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54983. edgeSquaredLength = this._edge.lengthSquared();
  54984. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54985. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54986. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54987. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54988. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54989. lowestRoot = getLowestRoot(a, b, c, t);
  54990. if (lowestRoot.found) {
  54991. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54992. if (f >= 0.0 && f <= 1.0) {
  54993. t = lowestRoot.root;
  54994. found = true;
  54995. this._edge.scaleInPlace(f);
  54996. p2.addToRef(this._edge, this._collisionPoint);
  54997. }
  54998. }
  54999. p1.subtractToRef(p3, this._edge);
  55000. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55001. edgeSquaredLength = this._edge.lengthSquared();
  55002. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55003. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55004. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55005. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55006. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55007. lowestRoot = getLowestRoot(a, b, c, t);
  55008. if (lowestRoot.found) {
  55009. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55010. if (f >= 0.0 && f <= 1.0) {
  55011. t = lowestRoot.root;
  55012. found = true;
  55013. this._edge.scaleInPlace(f);
  55014. p3.addToRef(this._edge, this._collisionPoint);
  55015. }
  55016. }
  55017. }
  55018. if (found) {
  55019. var distToCollision = t * this._velocity.length();
  55020. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55021. if (!this.intersectionPoint) {
  55022. this.intersectionPoint = this._collisionPoint.clone();
  55023. }
  55024. else {
  55025. this.intersectionPoint.copyFrom(this._collisionPoint);
  55026. }
  55027. this._nearestDistance = distToCollision;
  55028. this.collisionFound = true;
  55029. }
  55030. }
  55031. };
  55032. /** @hidden */
  55033. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55034. for (var i = indexStart; i < indexEnd; i += 3) {
  55035. var p1 = pts[indices[i] - decal];
  55036. var p2 = pts[indices[i + 1] - decal];
  55037. var p3 = pts[indices[i + 2] - decal];
  55038. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55039. }
  55040. };
  55041. /** @hidden */
  55042. Collider.prototype._getResponse = function (pos, vel) {
  55043. pos.addToRef(vel, this._destinationPoint);
  55044. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55045. this._basePoint.addToRef(vel, pos);
  55046. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55047. this._slidePlaneNormal.normalize();
  55048. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55049. pos.addInPlace(this._displacementVector);
  55050. this.intersectionPoint.addInPlace(this._displacementVector);
  55051. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55052. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55053. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55054. };
  55055. return Collider;
  55056. }());
  55057. BABYLON.Collider = Collider;
  55058. })(BABYLON || (BABYLON = {}));
  55059. //# sourceMappingURL=babylon.collider.js.map
  55060. var BABYLON;
  55061. (function (BABYLON) {
  55062. //WebWorker code will be inserted to this variable.
  55063. BABYLON.CollisionWorker = "";
  55064. /** Defines supported task for worker process */
  55065. var WorkerTaskType;
  55066. (function (WorkerTaskType) {
  55067. /** Initialization */
  55068. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55069. /** Update of geometry */
  55070. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55071. /** Evaluate collision */
  55072. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55073. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55074. /** Defines kind of replies returned by worker */
  55075. var WorkerReplyType;
  55076. (function (WorkerReplyType) {
  55077. /** Success */
  55078. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55079. /** Unkown error */
  55080. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55081. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55082. var CollisionCoordinatorWorker = /** @class */ (function () {
  55083. function CollisionCoordinatorWorker() {
  55084. var _this = this;
  55085. this._scaledPosition = BABYLON.Vector3.Zero();
  55086. this._scaledVelocity = BABYLON.Vector3.Zero();
  55087. this.onMeshUpdated = function (transformNode) {
  55088. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55089. };
  55090. this.onGeometryUpdated = function (geometry) {
  55091. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55092. };
  55093. this._afterRender = function () {
  55094. if (!_this._init)
  55095. return;
  55096. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55097. return;
  55098. }
  55099. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55100. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55101. if (_this._runningUpdated > 4) {
  55102. return;
  55103. }
  55104. ++_this._runningUpdated;
  55105. var payload = {
  55106. updatedMeshes: _this._addUpdateMeshesList,
  55107. updatedGeometries: _this._addUpdateGeometriesList,
  55108. removedGeometries: _this._toRemoveGeometryArray,
  55109. removedMeshes: _this._toRemoveMeshesArray
  55110. };
  55111. var message = {
  55112. payload: payload,
  55113. taskType: WorkerTaskType.UPDATE
  55114. };
  55115. var serializable = [];
  55116. for (var id in payload.updatedGeometries) {
  55117. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55118. //prepare transferables
  55119. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55120. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55121. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55122. }
  55123. }
  55124. _this._worker.postMessage(message, serializable);
  55125. _this._addUpdateMeshesList = {};
  55126. _this._addUpdateGeometriesList = {};
  55127. _this._toRemoveGeometryArray = [];
  55128. _this._toRemoveMeshesArray = [];
  55129. };
  55130. this._onMessageFromWorker = function (e) {
  55131. var returnData = e.data;
  55132. if (returnData.error != WorkerReplyType.SUCCESS) {
  55133. //TODO what errors can be returned from the worker?
  55134. BABYLON.Tools.Warn("error returned from worker!");
  55135. return;
  55136. }
  55137. switch (returnData.taskType) {
  55138. case WorkerTaskType.INIT:
  55139. _this._init = true;
  55140. //Update the worked with ALL of the scene's current state
  55141. _this._scene.meshes.forEach(function (mesh) {
  55142. _this.onMeshAdded(mesh);
  55143. });
  55144. _this._scene.getGeometries().forEach(function (geometry) {
  55145. _this.onGeometryAdded(geometry);
  55146. });
  55147. break;
  55148. case WorkerTaskType.UPDATE:
  55149. _this._runningUpdated--;
  55150. break;
  55151. case WorkerTaskType.COLLIDE:
  55152. var returnPayload = returnData.payload;
  55153. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55154. return;
  55155. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55156. if (callback) {
  55157. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55158. if (mesh) {
  55159. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55160. }
  55161. }
  55162. //cleanup
  55163. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55164. break;
  55165. }
  55166. };
  55167. this._collisionsCallbackArray = [];
  55168. this._init = false;
  55169. this._runningUpdated = 0;
  55170. this._addUpdateMeshesList = {};
  55171. this._addUpdateGeometriesList = {};
  55172. this._toRemoveGeometryArray = [];
  55173. this._toRemoveMeshesArray = [];
  55174. }
  55175. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55176. if (!this._init)
  55177. return;
  55178. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55179. return;
  55180. position.divideToRef(collider._radius, this._scaledPosition);
  55181. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55182. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55183. var payload = {
  55184. collider: {
  55185. position: this._scaledPosition.asArray(),
  55186. velocity: this._scaledVelocity.asArray(),
  55187. radius: collider._radius.asArray()
  55188. },
  55189. collisionId: collisionIndex,
  55190. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55191. maximumRetry: maximumRetry
  55192. };
  55193. var message = {
  55194. payload: payload,
  55195. taskType: WorkerTaskType.COLLIDE
  55196. };
  55197. this._worker.postMessage(message);
  55198. };
  55199. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55200. this._scene = scene;
  55201. this._scene.registerAfterRender(this._afterRender);
  55202. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55203. this._worker = new Worker(workerUrl);
  55204. this._worker.onmessage = this._onMessageFromWorker;
  55205. var message = {
  55206. payload: {},
  55207. taskType: WorkerTaskType.INIT
  55208. };
  55209. this._worker.postMessage(message);
  55210. };
  55211. CollisionCoordinatorWorker.prototype.destroy = function () {
  55212. this._scene.unregisterAfterRender(this._afterRender);
  55213. this._worker.terminate();
  55214. };
  55215. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55216. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55217. this.onMeshUpdated(mesh);
  55218. };
  55219. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55220. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55221. };
  55222. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55223. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55224. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55225. this.onGeometryUpdated(geometry);
  55226. };
  55227. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55228. this._toRemoveGeometryArray.push(geometry.id);
  55229. };
  55230. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55231. var submeshes = [];
  55232. if (mesh.subMeshes) {
  55233. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55234. var boundingInfo = sm.getBoundingInfo();
  55235. return {
  55236. position: idx,
  55237. verticesStart: sm.verticesStart,
  55238. verticesCount: sm.verticesCount,
  55239. indexStart: sm.indexStart,
  55240. indexCount: sm.indexCount,
  55241. hasMaterial: !!sm.getMaterial(),
  55242. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55243. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55244. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55245. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55246. };
  55247. });
  55248. }
  55249. var geometryId = null;
  55250. if (mesh instanceof BABYLON.Mesh) {
  55251. var geometry = mesh.geometry;
  55252. geometryId = geometry ? geometry.id : null;
  55253. }
  55254. else if (mesh instanceof BABYLON.InstancedMesh) {
  55255. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55256. geometryId = geometry ? geometry.id : null;
  55257. }
  55258. var boundingInfo = mesh.getBoundingInfo();
  55259. return {
  55260. uniqueId: mesh.uniqueId,
  55261. id: mesh.id,
  55262. name: mesh.name,
  55263. geometryId: geometryId,
  55264. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55265. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55266. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55267. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55268. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55269. subMeshes: submeshes,
  55270. checkCollisions: mesh.checkCollisions
  55271. };
  55272. };
  55273. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55274. return {
  55275. id: geometry.id,
  55276. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55277. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55278. indices: new Uint32Array(geometry.getIndices() || []),
  55279. };
  55280. };
  55281. return CollisionCoordinatorWorker;
  55282. }());
  55283. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55284. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55285. function CollisionCoordinatorLegacy() {
  55286. this._scaledPosition = BABYLON.Vector3.Zero();
  55287. this._scaledVelocity = BABYLON.Vector3.Zero();
  55288. this._finalPosition = BABYLON.Vector3.Zero();
  55289. }
  55290. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55291. position.divideToRef(collider._radius, this._scaledPosition);
  55292. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55293. collider.collidedMesh = null;
  55294. collider._retry = 0;
  55295. collider._initialVelocity = this._scaledVelocity;
  55296. collider._initialPosition = this._scaledPosition;
  55297. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55298. this._finalPosition.multiplyInPlace(collider._radius);
  55299. //run the callback
  55300. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55301. };
  55302. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55303. this._scene = scene;
  55304. };
  55305. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55306. //Legacy need no destruction method.
  55307. };
  55308. //No update in legacy mode
  55309. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55310. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55311. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55312. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55313. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55314. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55315. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55316. if (excludedMesh === void 0) { excludedMesh = null; }
  55317. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55318. if (collider._retry >= maximumRetry) {
  55319. finalPosition.copyFrom(position);
  55320. return;
  55321. }
  55322. // Check if this is a mesh else camera or -1
  55323. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55324. collider._initialize(position, velocity, closeDistance);
  55325. // Check all meshes
  55326. for (var index = 0; index < this._scene.meshes.length; index++) {
  55327. var mesh = this._scene.meshes[index];
  55328. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55329. mesh._checkCollision(collider);
  55330. }
  55331. }
  55332. if (!collider.collisionFound) {
  55333. position.addToRef(velocity, finalPosition);
  55334. return;
  55335. }
  55336. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55337. collider._getResponse(position, velocity);
  55338. }
  55339. if (velocity.length() <= closeDistance) {
  55340. finalPosition.copyFrom(position);
  55341. return;
  55342. }
  55343. collider._retry++;
  55344. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55345. };
  55346. return CollisionCoordinatorLegacy;
  55347. }());
  55348. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55349. })(BABYLON || (BABYLON = {}));
  55350. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55351. var BABYLON;
  55352. (function (BABYLON) {
  55353. /**
  55354. * A particle represents one of the element emitted by a particle system.
  55355. * This is mainly define by its coordinates, direction, velocity and age.
  55356. */
  55357. var Particle = /** @class */ (function () {
  55358. /**
  55359. * Creates a new instance Particle
  55360. * @param particleSystem the particle system the particle belongs to
  55361. */
  55362. function Particle(
  55363. /**
  55364. * particleSystem the particle system the particle belongs to.
  55365. */
  55366. particleSystem) {
  55367. this.particleSystem = particleSystem;
  55368. /**
  55369. * The world position of the particle in the scene.
  55370. */
  55371. this.position = BABYLON.Vector3.Zero();
  55372. /**
  55373. * The world direction of the particle in the scene.
  55374. */
  55375. this.direction = BABYLON.Vector3.Zero();
  55376. /**
  55377. * The color of the particle.
  55378. */
  55379. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55380. /**
  55381. * The color change of the particle per step.
  55382. */
  55383. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55384. /**
  55385. * Defines how long will the life of the particle be.
  55386. */
  55387. this.lifeTime = 1.0;
  55388. /**
  55389. * The current age of the particle.
  55390. */
  55391. this.age = 0;
  55392. /**
  55393. * The current size of the particle.
  55394. */
  55395. this.size = 0;
  55396. /**
  55397. * The current scale of the particle.
  55398. */
  55399. this.scale = new BABYLON.Vector2(1, 1);
  55400. /**
  55401. * The current angle of the particle.
  55402. */
  55403. this.angle = 0;
  55404. /**
  55405. * Defines how fast is the angle changing.
  55406. */
  55407. this.angularSpeed = 0;
  55408. /**
  55409. * Defines the cell index used by the particle to be rendered from a sprite.
  55410. */
  55411. this.cellIndex = 0;
  55412. /** @hidden */
  55413. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55414. /** @hidden */
  55415. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55416. /** @hidden */
  55417. this._currentSize1 = 0;
  55418. /** @hidden */
  55419. this._currentSize2 = 0;
  55420. /** @hidden */
  55421. this._currentAngularSpeed1 = 0;
  55422. /** @hidden */
  55423. this._currentAngularSpeed2 = 0;
  55424. /** @hidden */
  55425. this._currentVelocity1 = 0;
  55426. /** @hidden */
  55427. this._currentVelocity2 = 0;
  55428. /** @hidden */
  55429. this._currentLimitVelocity1 = 0;
  55430. /** @hidden */
  55431. this._currentLimitVelocity2 = 0;
  55432. if (!this.particleSystem.isAnimationSheetEnabled) {
  55433. return;
  55434. }
  55435. this.updateCellInfoFromSystem();
  55436. }
  55437. Particle.prototype.updateCellInfoFromSystem = function () {
  55438. this.cellIndex = this.particleSystem.startSpriteCellID;
  55439. };
  55440. /**
  55441. * Defines how the sprite cell index is updated for the particle
  55442. */
  55443. Particle.prototype.updateCellIndex = function () {
  55444. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55445. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55446. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55447. };
  55448. /**
  55449. * Copy the properties of particle to another one.
  55450. * @param other the particle to copy the information to.
  55451. */
  55452. Particle.prototype.copyTo = function (other) {
  55453. other.position.copyFrom(this.position);
  55454. if (this._initialDirection) {
  55455. if (other._initialDirection) {
  55456. other._initialDirection.copyFrom(this._initialDirection);
  55457. }
  55458. else {
  55459. other._initialDirection = this._initialDirection.clone();
  55460. }
  55461. }
  55462. else {
  55463. other._initialDirection = null;
  55464. }
  55465. other.direction.copyFrom(this.direction);
  55466. other.color.copyFrom(this.color);
  55467. other.colorStep.copyFrom(this.colorStep);
  55468. other.lifeTime = this.lifeTime;
  55469. other.age = this.age;
  55470. other.size = this.size;
  55471. other.scale.copyFrom(this.scale);
  55472. other.angle = this.angle;
  55473. other.angularSpeed = this.angularSpeed;
  55474. other.particleSystem = this.particleSystem;
  55475. other.cellIndex = this.cellIndex;
  55476. if (this._currentColorGradient) {
  55477. other._currentColorGradient = this._currentColorGradient;
  55478. other._currentColor1.copyFrom(this._currentColor1);
  55479. other._currentColor2.copyFrom(this._currentColor2);
  55480. }
  55481. if (this._currentSizeGradient) {
  55482. other._currentSizeGradient = this._currentSizeGradient;
  55483. other._currentSize1 = this._currentSize1;
  55484. other._currentSize2 = this._currentSize2;
  55485. }
  55486. if (this._currentAngularSpeedGradient) {
  55487. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55488. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55489. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55490. }
  55491. if (this._currentVelocityGradient) {
  55492. other._currentVelocityGradient = this._currentVelocityGradient;
  55493. other._currentVelocity1 = this._currentVelocity1;
  55494. other._currentVelocity2 = this._currentVelocity2;
  55495. }
  55496. if (this._currentLimitVelocityGradient) {
  55497. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55498. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55499. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55500. }
  55501. if (this.particleSystem.isAnimationSheetEnabled) {
  55502. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55503. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55504. }
  55505. };
  55506. return Particle;
  55507. }());
  55508. BABYLON.Particle = Particle;
  55509. })(BABYLON || (BABYLON = {}));
  55510. //# sourceMappingURL=babylon.particle.js.map
  55511. var BABYLON;
  55512. (function (BABYLON) {
  55513. /**
  55514. * This represents the base class for particle system in Babylon.
  55515. * 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.
  55516. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55517. * @example https://doc.babylonjs.com/babylon101/particles
  55518. */
  55519. var BaseParticleSystem = /** @class */ (function () {
  55520. /**
  55521. * Instantiates a particle system.
  55522. * 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.
  55523. * @param name The name of the particle system
  55524. */
  55525. function BaseParticleSystem(name) {
  55526. /**
  55527. * List of animations used by the particle system.
  55528. */
  55529. this.animations = [];
  55530. /**
  55531. * The rendering group used by the Particle system to chose when to render.
  55532. */
  55533. this.renderingGroupId = 0;
  55534. /**
  55535. * The emitter represents the Mesh or position we are attaching the particle system to.
  55536. */
  55537. this.emitter = null;
  55538. /**
  55539. * The maximum number of particles to emit per frame
  55540. */
  55541. this.emitRate = 10;
  55542. /**
  55543. * If you want to launch only a few particles at once, that can be done, as well.
  55544. */
  55545. this.manualEmitCount = -1;
  55546. /**
  55547. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55548. */
  55549. this.updateSpeed = 0.01;
  55550. /**
  55551. * The amount of time the particle system is running (depends of the overall update speed).
  55552. */
  55553. this.targetStopDuration = 0;
  55554. /**
  55555. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55556. */
  55557. this.disposeOnStop = false;
  55558. /**
  55559. * Minimum power of emitting particles.
  55560. */
  55561. this.minEmitPower = 1;
  55562. /**
  55563. * Maximum power of emitting particles.
  55564. */
  55565. this.maxEmitPower = 1;
  55566. /**
  55567. * Minimum life time of emitting particles.
  55568. */
  55569. this.minLifeTime = 1;
  55570. /**
  55571. * Maximum life time of emitting particles.
  55572. */
  55573. this.maxLifeTime = 1;
  55574. /**
  55575. * Minimum Size of emitting particles.
  55576. */
  55577. this.minSize = 1;
  55578. /**
  55579. * Maximum Size of emitting particles.
  55580. */
  55581. this.maxSize = 1;
  55582. /**
  55583. * Minimum scale of emitting particles on X axis.
  55584. */
  55585. this.minScaleX = 1;
  55586. /**
  55587. * Maximum scale of emitting particles on X axis.
  55588. */
  55589. this.maxScaleX = 1;
  55590. /**
  55591. * Minimum scale of emitting particles on Y axis.
  55592. */
  55593. this.minScaleY = 1;
  55594. /**
  55595. * Maximum scale of emitting particles on Y axis.
  55596. */
  55597. this.maxScaleY = 1;
  55598. /**
  55599. * Gets or sets the minimal initial rotation in radians.
  55600. */
  55601. this.minInitialRotation = 0;
  55602. /**
  55603. * Gets or sets the maximal initial rotation in radians.
  55604. */
  55605. this.maxInitialRotation = 0;
  55606. /**
  55607. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55608. */
  55609. this.minAngularSpeed = 0;
  55610. /**
  55611. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55612. */
  55613. this.maxAngularSpeed = 0;
  55614. /**
  55615. * The layer mask we are rendering the particles through.
  55616. */
  55617. this.layerMask = 0x0FFFFFFF;
  55618. /**
  55619. * This can help using your own shader to render the particle system.
  55620. * The according effect will be created
  55621. */
  55622. this.customShader = null;
  55623. /**
  55624. * By default particle system starts as soon as they are created. This prevents the
  55625. * automatic start to happen and let you decide when to start emitting particles.
  55626. */
  55627. this.preventAutoStart = false;
  55628. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55629. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55630. /**
  55631. * Callback triggered when the particle animation is ending.
  55632. */
  55633. this.onAnimationEnd = null;
  55634. /**
  55635. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55636. */
  55637. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55638. /**
  55639. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55640. * to override the particles.
  55641. */
  55642. this.forceDepthWrite = false;
  55643. /** 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 */
  55644. this.preWarmCycles = 0;
  55645. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55646. this.preWarmStepOffset = 1;
  55647. /**
  55648. * 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)
  55649. */
  55650. this.spriteCellChangeSpeed = 1;
  55651. /**
  55652. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55653. */
  55654. this.startSpriteCellID = 0;
  55655. /**
  55656. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55657. */
  55658. this.endSpriteCellID = 0;
  55659. /**
  55660. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55661. */
  55662. this.spriteCellWidth = 0;
  55663. /**
  55664. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55665. */
  55666. this.spriteCellHeight = 0;
  55667. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55668. this.translationPivot = new BABYLON.Vector2(0, 0);
  55669. /**
  55670. * You can use gravity if you want to give an orientation to your particles.
  55671. */
  55672. this.gravity = BABYLON.Vector3.Zero();
  55673. this._colorGradients = null;
  55674. this._sizeGradients = null;
  55675. this._lifeTimeGradients = null;
  55676. this._angularSpeedGradients = null;
  55677. this._velocityGradients = null;
  55678. this._limitVelocityGradients = null;
  55679. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55680. this.limitVelocityDamping = 0.4;
  55681. /**
  55682. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55683. */
  55684. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55685. /**
  55686. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55687. */
  55688. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55689. /**
  55690. * Color the particle will have at the end of its lifetime
  55691. */
  55692. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55693. /**
  55694. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55695. */
  55696. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55697. /**
  55698. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55699. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55700. */
  55701. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55702. this._isBillboardBased = true;
  55703. /**
  55704. * Local cache of defines for image processing.
  55705. */
  55706. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55707. this.id = name;
  55708. this.name = name;
  55709. }
  55710. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55711. /**
  55712. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55713. */
  55714. get: function () {
  55715. return this._isAnimationSheetEnabled;
  55716. },
  55717. set: function (value) {
  55718. if (this._isAnimationSheetEnabled == value) {
  55719. return;
  55720. }
  55721. this._isAnimationSheetEnabled = value;
  55722. this._reset();
  55723. },
  55724. enumerable: true,
  55725. configurable: true
  55726. });
  55727. /**
  55728. * Gets the current list of limit velocity gradients.
  55729. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55730. * @returns the list of limit velocity gradients
  55731. */
  55732. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55733. return this._limitVelocityGradients;
  55734. };
  55735. /**
  55736. * Gets the current list of color gradients.
  55737. * You must use addColorGradient and removeColorGradient to udpate this list
  55738. * @returns the list of color gradients
  55739. */
  55740. BaseParticleSystem.prototype.getColorGradients = function () {
  55741. return this._colorGradients;
  55742. };
  55743. /**
  55744. * Gets the current list of size gradients.
  55745. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55746. * @returns the list of size gradients
  55747. */
  55748. BaseParticleSystem.prototype.getSizeGradients = function () {
  55749. return this._sizeGradients;
  55750. };
  55751. /**
  55752. * Gets the current list of life time gradients.
  55753. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55754. * @returns the list of life time gradients
  55755. */
  55756. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55757. return this._lifeTimeGradients;
  55758. };
  55759. /**
  55760. * Gets the current list of angular speed gradients.
  55761. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55762. * @returns the list of angular speed gradients
  55763. */
  55764. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55765. return this._angularSpeedGradients;
  55766. };
  55767. /**
  55768. * Gets the current list of velocity gradients.
  55769. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55770. * @returns the list of velocity gradients
  55771. */
  55772. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55773. return this._velocityGradients;
  55774. };
  55775. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55776. /**
  55777. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55778. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55779. */
  55780. get: function () {
  55781. if (this.particleEmitterType.direction1) {
  55782. return this.particleEmitterType.direction1;
  55783. }
  55784. return BABYLON.Vector3.Zero();
  55785. },
  55786. set: function (value) {
  55787. if (this.particleEmitterType.direction1) {
  55788. this.particleEmitterType.direction1 = value;
  55789. }
  55790. },
  55791. enumerable: true,
  55792. configurable: true
  55793. });
  55794. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55795. /**
  55796. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55797. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55798. */
  55799. get: function () {
  55800. if (this.particleEmitterType.direction2) {
  55801. return this.particleEmitterType.direction2;
  55802. }
  55803. return BABYLON.Vector3.Zero();
  55804. },
  55805. set: function (value) {
  55806. if (this.particleEmitterType.direction2) {
  55807. this.particleEmitterType.direction2 = value;
  55808. }
  55809. },
  55810. enumerable: true,
  55811. configurable: true
  55812. });
  55813. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55814. /**
  55815. * 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.
  55816. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55817. */
  55818. get: function () {
  55819. if (this.particleEmitterType.minEmitBox) {
  55820. return this.particleEmitterType.minEmitBox;
  55821. }
  55822. return BABYLON.Vector3.Zero();
  55823. },
  55824. set: function (value) {
  55825. if (this.particleEmitterType.minEmitBox) {
  55826. this.particleEmitterType.minEmitBox = value;
  55827. }
  55828. },
  55829. enumerable: true,
  55830. configurable: true
  55831. });
  55832. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55833. /**
  55834. * 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.
  55835. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55836. */
  55837. get: function () {
  55838. if (this.particleEmitterType.maxEmitBox) {
  55839. return this.particleEmitterType.maxEmitBox;
  55840. }
  55841. return BABYLON.Vector3.Zero();
  55842. },
  55843. set: function (value) {
  55844. if (this.particleEmitterType.maxEmitBox) {
  55845. this.particleEmitterType.maxEmitBox = value;
  55846. }
  55847. },
  55848. enumerable: true,
  55849. configurable: true
  55850. });
  55851. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55852. /**
  55853. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55854. */
  55855. get: function () {
  55856. return this._isBillboardBased;
  55857. },
  55858. set: function (value) {
  55859. if (this._isBillboardBased === value) {
  55860. return;
  55861. }
  55862. this._isBillboardBased = value;
  55863. this._reset();
  55864. },
  55865. enumerable: true,
  55866. configurable: true
  55867. });
  55868. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55869. /**
  55870. * Gets the image processing configuration used either in this material.
  55871. */
  55872. get: function () {
  55873. return this._imageProcessingConfiguration;
  55874. },
  55875. /**
  55876. * Sets the Default image processing configuration used either in the this material.
  55877. *
  55878. * If sets to null, the scene one is in use.
  55879. */
  55880. set: function (value) {
  55881. this._attachImageProcessingConfiguration(value);
  55882. },
  55883. enumerable: true,
  55884. configurable: true
  55885. });
  55886. /**
  55887. * Attaches a new image processing configuration to the Standard Material.
  55888. * @param configuration
  55889. */
  55890. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55891. if (configuration === this._imageProcessingConfiguration) {
  55892. return;
  55893. }
  55894. // Pick the scene configuration if needed.
  55895. if (!configuration) {
  55896. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55897. }
  55898. else {
  55899. this._imageProcessingConfiguration = configuration;
  55900. }
  55901. };
  55902. /** @hidden */
  55903. BaseParticleSystem.prototype._reset = function () {
  55904. };
  55905. /**
  55906. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55907. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55908. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55909. * @returns the emitter
  55910. */
  55911. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55912. var particleEmitter = new BABYLON.PointParticleEmitter();
  55913. particleEmitter.direction1 = direction1;
  55914. particleEmitter.direction2 = direction2;
  55915. this.particleEmitterType = particleEmitter;
  55916. return particleEmitter;
  55917. };
  55918. /**
  55919. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55920. * @param radius The radius of the hemisphere to emit from
  55921. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55922. * @returns the emitter
  55923. */
  55924. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55925. if (radius === void 0) { radius = 1; }
  55926. if (radiusRange === void 0) { radiusRange = 1; }
  55927. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55928. this.particleEmitterType = particleEmitter;
  55929. return particleEmitter;
  55930. };
  55931. /**
  55932. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55933. * @param radius The radius of the sphere to emit from
  55934. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55935. * @returns the emitter
  55936. */
  55937. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55938. if (radius === void 0) { radius = 1; }
  55939. if (radiusRange === void 0) { radiusRange = 1; }
  55940. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55941. this.particleEmitterType = particleEmitter;
  55942. return particleEmitter;
  55943. };
  55944. /**
  55945. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55946. * @param radius The radius of the sphere to emit from
  55947. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55948. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55949. * @returns the emitter
  55950. */
  55951. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55952. if (radius === void 0) { radius = 1; }
  55953. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55954. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55955. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55956. this.particleEmitterType = particleEmitter;
  55957. return particleEmitter;
  55958. };
  55959. /**
  55960. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55961. * @param radius The radius of the cone to emit from
  55962. * @param angle The base angle of the cone
  55963. * @returns the emitter
  55964. */
  55965. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55966. if (radius === void 0) { radius = 1; }
  55967. if (angle === void 0) { angle = Math.PI / 4; }
  55968. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55969. this.particleEmitterType = particleEmitter;
  55970. return particleEmitter;
  55971. };
  55972. /**
  55973. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55974. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55975. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55976. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55977. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55978. * @returns the emitter
  55979. */
  55980. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55981. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55982. this.particleEmitterType = particleEmitter;
  55983. this.direction1 = direction1;
  55984. this.direction2 = direction2;
  55985. this.minEmitBox = minEmitBox;
  55986. this.maxEmitBox = maxEmitBox;
  55987. return particleEmitter;
  55988. };
  55989. /**
  55990. * Source color is added to the destination color without alpha affecting the result.
  55991. */
  55992. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55993. /**
  55994. * Blend current color and particle color using particle’s alpha.
  55995. */
  55996. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55997. /**
  55998. * Add current color and particle color multiplied by particle’s alpha.
  55999. */
  56000. BaseParticleSystem.BLENDMODE_ADD = 2;
  56001. return BaseParticleSystem;
  56002. }());
  56003. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56004. })(BABYLON || (BABYLON = {}));
  56005. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56006. var BABYLON;
  56007. (function (BABYLON) {
  56008. /**
  56009. * This represents a particle system in Babylon.
  56010. * 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.
  56011. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56012. * @example https://doc.babylonjs.com/babylon101/particles
  56013. */
  56014. var ParticleSystem = /** @class */ (function (_super) {
  56015. __extends(ParticleSystem, _super);
  56016. /**
  56017. * Instantiates a particle system.
  56018. * 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.
  56019. * @param name The name of the particle system
  56020. * @param capacity The max number of particles alive at the same time
  56021. * @param scene The scene the particle system belongs to
  56022. * @param customEffect a custom effect used to change the way particles are rendered by default
  56023. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56024. * @param epsilon Offset used to render the particles
  56025. */
  56026. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56027. if (customEffect === void 0) { customEffect = null; }
  56028. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56029. if (epsilon === void 0) { epsilon = 0.01; }
  56030. var _this = _super.call(this, name) || this;
  56031. /**
  56032. * An event triggered when the system is disposed
  56033. */
  56034. _this.onDisposeObservable = new BABYLON.Observable();
  56035. _this._particles = new Array();
  56036. _this._stockParticles = new Array();
  56037. _this._newPartsExcess = 0;
  56038. _this._vertexBuffers = {};
  56039. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56040. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56041. _this._scaledDirection = BABYLON.Vector3.Zero();
  56042. _this._scaledGravity = BABYLON.Vector3.Zero();
  56043. _this._currentRenderId = -1;
  56044. _this._useInstancing = false;
  56045. _this._started = false;
  56046. _this._stopped = false;
  56047. _this._actualFrame = 0;
  56048. // start of sub system methods
  56049. /**
  56050. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56051. * Its lifetime will start back at 0.
  56052. */
  56053. _this.recycleParticle = function (particle) {
  56054. var lastParticle = _this._particles.pop();
  56055. if (lastParticle !== particle) {
  56056. lastParticle.copyTo(particle);
  56057. }
  56058. _this._stockParticles.push(lastParticle);
  56059. };
  56060. _this._createParticle = function () {
  56061. var particle;
  56062. if (_this._stockParticles.length !== 0) {
  56063. particle = _this._stockParticles.pop();
  56064. particle.age = 0;
  56065. particle._currentColorGradient = null;
  56066. particle.cellIndex = _this.startSpriteCellID;
  56067. }
  56068. else {
  56069. particle = new BABYLON.Particle(_this);
  56070. }
  56071. return particle;
  56072. };
  56073. _this._emitFromParticle = function (particle) {
  56074. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56075. return;
  56076. }
  56077. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56078. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56079. subSystem._rootParticleSystem = _this;
  56080. _this.activeSubSystems.push(subSystem);
  56081. subSystem.start();
  56082. };
  56083. _this._capacity = capacity;
  56084. _this._epsilon = epsilon;
  56085. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56086. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56087. // Setup the default processing configuration to the scene.
  56088. _this._attachImageProcessingConfiguration(null);
  56089. _this._customEffect = customEffect;
  56090. _this._scene.particleSystems.push(_this);
  56091. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56092. _this._createIndexBuffer();
  56093. _this._createVertexBuffers();
  56094. // Default emitter type
  56095. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56096. _this.updateFunction = function (particles) {
  56097. var noiseTextureData = null;
  56098. var noiseTextureSize = null;
  56099. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56100. noiseTextureData = (_this.noiseTexture.readPixels());
  56101. noiseTextureSize = _this.noiseTexture.getSize();
  56102. }
  56103. var _loop_1 = function () {
  56104. particle = particles[index];
  56105. particle.age += _this._scaledUpdateSpeed;
  56106. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56107. _this._emitFromParticle(particle);
  56108. _this.recycleParticle(particle);
  56109. index--;
  56110. return "continue";
  56111. }
  56112. else {
  56113. var ratio = particle.age / particle.lifeTime;
  56114. // Color
  56115. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56116. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56117. if (currentGradient !== particle._currentColorGradient) {
  56118. particle._currentColor1.copyFrom(particle._currentColor2);
  56119. nextGradient.getColorToRef(particle._currentColor2);
  56120. particle._currentColorGradient = currentGradient;
  56121. }
  56122. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56123. });
  56124. }
  56125. else {
  56126. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56127. particle.color.addInPlace(_this._scaledColorStep);
  56128. if (particle.color.a < 0) {
  56129. particle.color.a = 0;
  56130. }
  56131. }
  56132. // Angular speed
  56133. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56134. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56135. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56136. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56137. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56138. particle._currentAngularSpeedGradient = currentGradient;
  56139. }
  56140. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56141. });
  56142. }
  56143. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56144. // Direction
  56145. var directionScale_1 = _this._scaledUpdateSpeed;
  56146. /// Velocity
  56147. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56148. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56149. if (currentGradient !== particle._currentVelocityGradient) {
  56150. particle._currentVelocity1 = particle._currentVelocity2;
  56151. particle._currentVelocity2 = nextGradient.getFactor();
  56152. particle._currentVelocityGradient = currentGradient;
  56153. }
  56154. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56155. });
  56156. }
  56157. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56158. /// Limit velocity
  56159. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56160. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56161. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56162. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56163. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56164. particle._currentLimitVelocityGradient = currentGradient;
  56165. }
  56166. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56167. var currentVelocity = particle.direction.length();
  56168. if (currentVelocity > limitVelocity) {
  56169. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56170. }
  56171. });
  56172. }
  56173. particle.position.addInPlace(_this._scaledDirection);
  56174. // Noise
  56175. if (noiseTextureData && noiseTextureSize) {
  56176. var localPosition = BABYLON.Tmp.Vector3[0];
  56177. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56178. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56179. particle.position.subtractToRef(emitterPosition, localPosition);
  56180. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56181. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56182. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56183. var force = BABYLON.Tmp.Vector3[0];
  56184. var scaledForce = BABYLON.Tmp.Vector3[1];
  56185. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56186. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56187. particle.direction.addInPlace(scaledForce);
  56188. }
  56189. // Gravity
  56190. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56191. particle.direction.addInPlace(_this._scaledGravity);
  56192. // Size
  56193. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56194. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56195. if (currentGradient !== particle._currentSizeGradient) {
  56196. particle._currentSize1 = particle._currentSize2;
  56197. particle._currentSize2 = nextGradient.getFactor();
  56198. particle._currentSizeGradient = currentGradient;
  56199. }
  56200. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56201. });
  56202. }
  56203. if (_this._isAnimationSheetEnabled) {
  56204. particle.updateCellIndex();
  56205. }
  56206. }
  56207. };
  56208. var particle;
  56209. for (var index = 0; index < particles.length; index++) {
  56210. _loop_1();
  56211. }
  56212. };
  56213. return _this;
  56214. }
  56215. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56216. /**
  56217. * Sets a callback that will be triggered when the system is disposed
  56218. */
  56219. set: function (callback) {
  56220. if (this._onDisposeObserver) {
  56221. this.onDisposeObservable.remove(this._onDisposeObserver);
  56222. }
  56223. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56224. },
  56225. enumerable: true,
  56226. configurable: true
  56227. });
  56228. /**
  56229. * Get hosting scene
  56230. * @returns the scene
  56231. */
  56232. ParticleSystem.prototype.getScene = function () {
  56233. return this._scene;
  56234. };
  56235. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56236. //end of Sub-emitter
  56237. /**
  56238. * Gets the current list of active particles
  56239. */
  56240. get: function () {
  56241. return this._particles;
  56242. },
  56243. enumerable: true,
  56244. configurable: true
  56245. });
  56246. /**
  56247. * Returns the string "ParticleSystem"
  56248. * @returns a string containing the class name
  56249. */
  56250. ParticleSystem.prototype.getClassName = function () {
  56251. return "ParticleSystem";
  56252. };
  56253. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56254. var newGradient = new BABYLON.FactorGradient();
  56255. newGradient.gradient = gradient;
  56256. newGradient.factor1 = factor;
  56257. newGradient.factor2 = factor2;
  56258. factorGradients.push(newGradient);
  56259. factorGradients.sort(function (a, b) {
  56260. if (a.gradient < b.gradient) {
  56261. return -1;
  56262. }
  56263. else if (a.gradient > b.gradient) {
  56264. return 1;
  56265. }
  56266. return 0;
  56267. });
  56268. };
  56269. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56270. if (!factorGradients) {
  56271. return;
  56272. }
  56273. var index = 0;
  56274. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56275. var factorGradient = factorGradients_1[_i];
  56276. if (factorGradient.gradient === gradient) {
  56277. factorGradients.splice(index, 1);
  56278. break;
  56279. }
  56280. index++;
  56281. }
  56282. };
  56283. /**
  56284. * Adds a new life time gradient
  56285. * @param gradient defines the gradient to use (between 0 and 1)
  56286. * @param factor defines the life time factor to affect to the specified gradient
  56287. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56288. * @returns the current particle system
  56289. */
  56290. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56291. if (!this._lifeTimeGradients) {
  56292. this._lifeTimeGradients = [];
  56293. }
  56294. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56295. return this;
  56296. };
  56297. /**
  56298. * Remove a specific life time gradient
  56299. * @param gradient defines the gradient to remove
  56300. * @returns the current particle system
  56301. */
  56302. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56303. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56304. return this;
  56305. };
  56306. /**
  56307. * Adds a new size gradient
  56308. * @param gradient defines the gradient to use (between 0 and 1)
  56309. * @param factor defines the size factor to affect to the specified gradient
  56310. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56311. * @returns the current particle system
  56312. */
  56313. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56314. if (!this._sizeGradients) {
  56315. this._sizeGradients = [];
  56316. }
  56317. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56318. return this;
  56319. };
  56320. /**
  56321. * Remove a specific size gradient
  56322. * @param gradient defines the gradient to remove
  56323. * @returns the current particle system
  56324. */
  56325. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56326. this._removeFactorGradient(this._sizeGradients, gradient);
  56327. return this;
  56328. };
  56329. /**
  56330. * Adds a new angular speed gradient
  56331. * @param gradient defines the gradient to use (between 0 and 1)
  56332. * @param factor defines the angular speed to affect to the specified gradient
  56333. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56334. * @returns the current particle system
  56335. */
  56336. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56337. if (!this._angularSpeedGradients) {
  56338. this._angularSpeedGradients = [];
  56339. }
  56340. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56341. return this;
  56342. };
  56343. /**
  56344. * Remove a specific angular speed gradient
  56345. * @param gradient defines the gradient to remove
  56346. * @returns the current particle system
  56347. */
  56348. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56349. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56350. return this;
  56351. };
  56352. /**
  56353. * Adds a new velocity gradient
  56354. * @param gradient defines the gradient to use (between 0 and 1)
  56355. * @param factor defines the velocity to affect to the specified gradient
  56356. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56357. * @returns the current particle system
  56358. */
  56359. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56360. if (!this._velocityGradients) {
  56361. this._velocityGradients = [];
  56362. }
  56363. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56364. return this;
  56365. };
  56366. /**
  56367. * Remove a specific velocity gradient
  56368. * @param gradient defines the gradient to remove
  56369. * @returns the current particle system
  56370. */
  56371. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56372. this._removeFactorGradient(this._velocityGradients, gradient);
  56373. return this;
  56374. };
  56375. /**
  56376. * Adds a new limit velocity gradient
  56377. * @param gradient defines the gradient to use (between 0 and 1)
  56378. * @param factor defines the limit velocity value to affect to the specified gradient
  56379. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56380. * @returns the current particle system
  56381. */
  56382. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56383. if (!this._limitVelocityGradients) {
  56384. this._limitVelocityGradients = [];
  56385. }
  56386. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56387. return this;
  56388. };
  56389. /**
  56390. * Remove a specific limit velocity gradient
  56391. * @param gradient defines the gradient to remove
  56392. * @returns the current particle system
  56393. */
  56394. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56395. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56396. return this;
  56397. };
  56398. /**
  56399. * Adds a new color gradient
  56400. * @param gradient defines the gradient to use (between 0 and 1)
  56401. * @param color defines the color to affect to the specified gradient
  56402. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56403. */
  56404. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56405. if (!this._colorGradients) {
  56406. this._colorGradients = [];
  56407. }
  56408. var colorGradient = new BABYLON.ColorGradient();
  56409. colorGradient.gradient = gradient;
  56410. colorGradient.color1 = color;
  56411. colorGradient.color2 = color2;
  56412. this._colorGradients.push(colorGradient);
  56413. this._colorGradients.sort(function (a, b) {
  56414. if (a.gradient < b.gradient) {
  56415. return -1;
  56416. }
  56417. else if (a.gradient > b.gradient) {
  56418. return 1;
  56419. }
  56420. return 0;
  56421. });
  56422. return this;
  56423. };
  56424. /**
  56425. * Remove a specific color gradient
  56426. * @param gradient defines the gradient to remove
  56427. */
  56428. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56429. if (!this._colorGradients) {
  56430. return this;
  56431. }
  56432. var index = 0;
  56433. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56434. var colorGradient = _a[_i];
  56435. if (colorGradient.gradient === gradient) {
  56436. this._colorGradients.splice(index, 1);
  56437. break;
  56438. }
  56439. index++;
  56440. }
  56441. return this;
  56442. };
  56443. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56444. u = Math.abs(u) * 0.5 + 0.5;
  56445. v = Math.abs(v) * 0.5 + 0.5;
  56446. var wrappedU = ((u * width) % width) | 0;
  56447. var wrappedV = ((v * height) % height) | 0;
  56448. var position = (wrappedU + wrappedV * width) * 4;
  56449. return pixels[position] / 255;
  56450. };
  56451. ParticleSystem.prototype._reset = function () {
  56452. this._resetEffect();
  56453. };
  56454. ParticleSystem.prototype._resetEffect = function () {
  56455. if (this._vertexBuffer) {
  56456. this._vertexBuffer.dispose();
  56457. this._vertexBuffer = null;
  56458. }
  56459. if (this._spriteBuffer) {
  56460. this._spriteBuffer.dispose();
  56461. this._spriteBuffer = null;
  56462. }
  56463. this._createVertexBuffers();
  56464. };
  56465. ParticleSystem.prototype._createVertexBuffers = function () {
  56466. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56467. if (this._isAnimationSheetEnabled) {
  56468. this._vertexBufferSize += 1;
  56469. }
  56470. if (!this._isBillboardBased) {
  56471. this._vertexBufferSize += 3;
  56472. }
  56473. var engine = this._scene.getEngine();
  56474. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56475. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56476. var dataOffset = 0;
  56477. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56479. dataOffset += 3;
  56480. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56481. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56482. dataOffset += 4;
  56483. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56484. this._vertexBuffers["angle"] = options;
  56485. dataOffset += 1;
  56486. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56487. this._vertexBuffers["size"] = size;
  56488. dataOffset += 2;
  56489. if (this._isAnimationSheetEnabled) {
  56490. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56491. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56492. dataOffset += 1;
  56493. }
  56494. if (!this._isBillboardBased) {
  56495. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56496. this._vertexBuffers["direction"] = directionBuffer;
  56497. dataOffset += 3;
  56498. }
  56499. var offsets;
  56500. if (this._useInstancing) {
  56501. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56502. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56503. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56504. }
  56505. else {
  56506. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56507. dataOffset += 2;
  56508. }
  56509. this._vertexBuffers["offset"] = offsets;
  56510. };
  56511. ParticleSystem.prototype._createIndexBuffer = function () {
  56512. if (this._useInstancing) {
  56513. return;
  56514. }
  56515. var indices = [];
  56516. var index = 0;
  56517. for (var count = 0; count < this._capacity; count++) {
  56518. indices.push(index);
  56519. indices.push(index + 1);
  56520. indices.push(index + 2);
  56521. indices.push(index);
  56522. indices.push(index + 2);
  56523. indices.push(index + 3);
  56524. index += 4;
  56525. }
  56526. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56527. };
  56528. /**
  56529. * Gets the maximum number of particles active at the same time.
  56530. * @returns The max number of active particles.
  56531. */
  56532. ParticleSystem.prototype.getCapacity = function () {
  56533. return this._capacity;
  56534. };
  56535. /**
  56536. * Gets whether there are still active particles in the system.
  56537. * @returns True if it is alive, otherwise false.
  56538. */
  56539. ParticleSystem.prototype.isAlive = function () {
  56540. return this._alive;
  56541. };
  56542. /**
  56543. * Gets whether the system has been started.
  56544. * @returns True if it has been started, otherwise false.
  56545. */
  56546. ParticleSystem.prototype.isStarted = function () {
  56547. return this._started;
  56548. };
  56549. /**
  56550. * Starts the particle system and begins to emit
  56551. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56552. */
  56553. ParticleSystem.prototype.start = function (delay) {
  56554. var _this = this;
  56555. if (delay === void 0) { delay = 0; }
  56556. if (delay) {
  56557. setTimeout(function () {
  56558. _this.start(0);
  56559. }, delay);
  56560. return;
  56561. }
  56562. this._started = true;
  56563. this._stopped = false;
  56564. this._actualFrame = 0;
  56565. if (this.subEmitters && this.subEmitters.length != 0) {
  56566. this.activeSubSystems = new Array();
  56567. }
  56568. if (this.preWarmCycles) {
  56569. for (var index = 0; index < this.preWarmCycles; index++) {
  56570. this.animate(true);
  56571. }
  56572. }
  56573. };
  56574. /**
  56575. * Stops the particle system.
  56576. * @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.
  56577. */
  56578. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56579. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56580. this._stopped = true;
  56581. if (stopSubEmitters) {
  56582. this._stopSubEmitters();
  56583. }
  56584. };
  56585. // animation sheet
  56586. /**
  56587. * Remove all active particles
  56588. */
  56589. ParticleSystem.prototype.reset = function () {
  56590. this._stockParticles = [];
  56591. this._particles = [];
  56592. };
  56593. /**
  56594. * @hidden (for internal use only)
  56595. */
  56596. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56597. var offset = index * this._vertexBufferSize;
  56598. this._vertexData[offset++] = particle.position.x;
  56599. this._vertexData[offset++] = particle.position.y;
  56600. this._vertexData[offset++] = particle.position.z;
  56601. this._vertexData[offset++] = particle.color.r;
  56602. this._vertexData[offset++] = particle.color.g;
  56603. this._vertexData[offset++] = particle.color.b;
  56604. this._vertexData[offset++] = particle.color.a;
  56605. this._vertexData[offset++] = particle.angle;
  56606. this._vertexData[offset++] = particle.scale.x * particle.size;
  56607. this._vertexData[offset++] = particle.scale.y * particle.size;
  56608. if (this._isAnimationSheetEnabled) {
  56609. this._vertexData[offset++] = particle.cellIndex;
  56610. }
  56611. if (!this._isBillboardBased) {
  56612. if (particle._initialDirection) {
  56613. this._vertexData[offset++] = particle._initialDirection.x;
  56614. this._vertexData[offset++] = particle._initialDirection.y;
  56615. this._vertexData[offset++] = particle._initialDirection.z;
  56616. }
  56617. else {
  56618. this._vertexData[offset++] = particle.direction.x;
  56619. this._vertexData[offset++] = particle.direction.y;
  56620. this._vertexData[offset++] = particle.direction.z;
  56621. }
  56622. }
  56623. if (!this._useInstancing) {
  56624. if (this._isAnimationSheetEnabled) {
  56625. if (offsetX === 0)
  56626. offsetX = this._epsilon;
  56627. else if (offsetX === 1)
  56628. offsetX = 1 - this._epsilon;
  56629. if (offsetY === 0)
  56630. offsetY = this._epsilon;
  56631. else if (offsetY === 1)
  56632. offsetY = 1 - this._epsilon;
  56633. }
  56634. this._vertexData[offset++] = offsetX;
  56635. this._vertexData[offset++] = offsetY;
  56636. }
  56637. };
  56638. ParticleSystem.prototype._stopSubEmitters = function () {
  56639. if (!this.activeSubSystems) {
  56640. return;
  56641. }
  56642. this.activeSubSystems.forEach(function (subSystem) {
  56643. subSystem.stop(true);
  56644. });
  56645. this.activeSubSystems = new Array();
  56646. };
  56647. ParticleSystem.prototype._removeFromRoot = function () {
  56648. if (!this._rootParticleSystem) {
  56649. return;
  56650. }
  56651. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56652. if (index !== -1) {
  56653. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56654. }
  56655. };
  56656. // End of sub system methods
  56657. ParticleSystem.prototype._update = function (newParticles) {
  56658. // Update current
  56659. this._alive = this._particles.length > 0;
  56660. if (this.emitter.position) {
  56661. var emitterMesh = this.emitter;
  56662. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56663. }
  56664. else {
  56665. var emitterPosition = this.emitter;
  56666. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56667. }
  56668. this.updateFunction(this._particles);
  56669. // Add new ones
  56670. var particle;
  56671. var _loop_2 = function () {
  56672. if (this_1._particles.length === this_1._capacity) {
  56673. return "break";
  56674. }
  56675. particle = this_1._createParticle();
  56676. this_1._particles.push(particle);
  56677. // Emitter
  56678. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56679. if (this_1.startPositionFunction) {
  56680. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56681. }
  56682. else {
  56683. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56684. }
  56685. if (this_1.startDirectionFunction) {
  56686. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56687. }
  56688. else {
  56689. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56690. }
  56691. if (emitPower === 0) {
  56692. if (!particle._initialDirection) {
  56693. particle._initialDirection = particle.direction.clone();
  56694. }
  56695. else {
  56696. particle._initialDirection.copyFrom(particle.direction);
  56697. }
  56698. }
  56699. else {
  56700. particle._initialDirection = null;
  56701. }
  56702. particle.direction.scaleInPlace(emitPower);
  56703. // Life time
  56704. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56705. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56706. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56707. var factorGradient1 = currentGradient;
  56708. var factorGradient2 = nextGradient;
  56709. var lifeTime1 = factorGradient1.getFactor();
  56710. var lifeTime2 = factorGradient2.getFactor();
  56711. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56712. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56713. });
  56714. }
  56715. else {
  56716. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56717. }
  56718. // Size
  56719. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56720. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56721. }
  56722. else {
  56723. particle._currentSizeGradient = this_1._sizeGradients[0];
  56724. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56725. particle.size = particle._currentSize1;
  56726. if (this_1._sizeGradients.length > 1) {
  56727. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56728. }
  56729. else {
  56730. particle._currentSize2 = particle._currentSize1;
  56731. }
  56732. }
  56733. // Size and scale
  56734. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56735. // Angle
  56736. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56737. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56738. }
  56739. else {
  56740. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56741. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56742. particle._currentAngularSpeed1 = particle.angularSpeed;
  56743. if (this_1._angularSpeedGradients.length > 1) {
  56744. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56745. }
  56746. else {
  56747. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56748. }
  56749. }
  56750. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56751. // Velocity
  56752. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56753. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56754. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56755. if (this_1._velocityGradients.length > 1) {
  56756. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56757. }
  56758. else {
  56759. particle._currentVelocity2 = particle._currentVelocity1;
  56760. }
  56761. }
  56762. // Limit velocity
  56763. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56764. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56765. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56766. if (this_1._limitVelocityGradients.length > 1) {
  56767. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56768. }
  56769. else {
  56770. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56771. }
  56772. }
  56773. // Color
  56774. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56775. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56776. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56777. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56778. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56779. }
  56780. else {
  56781. particle._currentColorGradient = this_1._colorGradients[0];
  56782. particle._currentColorGradient.getColorToRef(particle.color);
  56783. particle._currentColor1.copyFrom(particle.color);
  56784. if (this_1._colorGradients.length > 1) {
  56785. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56786. }
  56787. else {
  56788. particle._currentColor2.copyFrom(particle.color);
  56789. }
  56790. }
  56791. // Sheet
  56792. if (this_1._isAnimationSheetEnabled) {
  56793. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56794. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56795. }
  56796. };
  56797. var this_1 = this, step;
  56798. for (var index = 0; index < newParticles; index++) {
  56799. var state_1 = _loop_2();
  56800. if (state_1 === "break")
  56801. break;
  56802. }
  56803. };
  56804. /** @hidden */
  56805. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56806. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56807. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56808. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56809. if (isAnimationSheetEnabled) {
  56810. attributeNamesOrOptions.push("cellIndex");
  56811. }
  56812. if (!isBillboardBased) {
  56813. attributeNamesOrOptions.push("direction");
  56814. }
  56815. return attributeNamesOrOptions;
  56816. };
  56817. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56818. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56819. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  56820. if (isAnimationSheetEnabled) {
  56821. effectCreationOption.push("particlesInfos");
  56822. }
  56823. return effectCreationOption;
  56824. };
  56825. ParticleSystem.prototype._getEffect = function () {
  56826. if (this._customEffect) {
  56827. return this._customEffect;
  56828. }
  56829. ;
  56830. var defines = [];
  56831. if (this._scene.clipPlane) {
  56832. defines.push("#define CLIPPLANE");
  56833. }
  56834. if (this._scene.clipPlane2) {
  56835. defines.push("#define CLIPPLANE2");
  56836. }
  56837. if (this._scene.clipPlane3) {
  56838. defines.push("#define CLIPPLANE3");
  56839. }
  56840. if (this._scene.clipPlane4) {
  56841. defines.push("#define CLIPPLANE4");
  56842. }
  56843. if (this._isAnimationSheetEnabled) {
  56844. defines.push("#define ANIMATESHEET");
  56845. }
  56846. if (this._isBillboardBased) {
  56847. defines.push("#define BILLBOARD");
  56848. switch (this.billboardMode) {
  56849. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56850. defines.push("#define BILLBOARDY");
  56851. break;
  56852. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56853. default:
  56854. break;
  56855. }
  56856. }
  56857. if (this._imageProcessingConfiguration) {
  56858. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  56859. defines.push(this._imageProcessingConfigurationDefines.toString());
  56860. }
  56861. // Effect
  56862. var join = defines.join("\n");
  56863. if (this._cachedDefines !== join) {
  56864. this._cachedDefines = join;
  56865. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56866. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56867. var samplers = ["diffuseSampler"];
  56868. if (BABYLON.ImageProcessingConfiguration) {
  56869. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  56870. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  56871. }
  56872. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56873. }
  56874. return this._effect;
  56875. };
  56876. /**
  56877. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56878. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56879. */
  56880. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56881. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56882. if (!this._started)
  56883. return;
  56884. if (!preWarmOnly) {
  56885. var effect = this._getEffect();
  56886. // Check
  56887. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56888. return;
  56889. if (this._currentRenderId === this._scene.getRenderId()) {
  56890. return;
  56891. }
  56892. this._currentRenderId = this._scene.getRenderId();
  56893. }
  56894. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56895. // determine the number of particles we need to create
  56896. var newParticles;
  56897. if (this.manualEmitCount > -1) {
  56898. newParticles = this.manualEmitCount;
  56899. this._newPartsExcess = 0;
  56900. this.manualEmitCount = 0;
  56901. }
  56902. else {
  56903. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56904. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56905. }
  56906. if (this._newPartsExcess > 1.0) {
  56907. newParticles += this._newPartsExcess >> 0;
  56908. this._newPartsExcess -= this._newPartsExcess >> 0;
  56909. }
  56910. this._alive = false;
  56911. if (!this._stopped) {
  56912. this._actualFrame += this._scaledUpdateSpeed;
  56913. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56914. this.stop();
  56915. }
  56916. else {
  56917. newParticles = 0;
  56918. }
  56919. this._update(newParticles);
  56920. // Stopped?
  56921. if (this._stopped) {
  56922. if (!this._alive) {
  56923. this._started = false;
  56924. if (this.onAnimationEnd) {
  56925. this.onAnimationEnd();
  56926. }
  56927. if (this.disposeOnStop) {
  56928. this._scene._toBeDisposed.push(this);
  56929. }
  56930. }
  56931. }
  56932. if (!preWarmOnly) {
  56933. // Update VBO
  56934. var offset = 0;
  56935. for (var index = 0; index < this._particles.length; index++) {
  56936. var particle = this._particles[index];
  56937. this._appendParticleVertices(offset, particle);
  56938. offset += this._useInstancing ? 1 : 4;
  56939. }
  56940. if (this._vertexBuffer) {
  56941. this._vertexBuffer.update(this._vertexData);
  56942. }
  56943. }
  56944. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56945. this.stop();
  56946. }
  56947. };
  56948. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56949. this._appendParticleVertex(offset++, particle, 0, 0);
  56950. if (!this._useInstancing) {
  56951. this._appendParticleVertex(offset++, particle, 1, 0);
  56952. this._appendParticleVertex(offset++, particle, 1, 1);
  56953. this._appendParticleVertex(offset++, particle, 0, 1);
  56954. }
  56955. };
  56956. /**
  56957. * Rebuilds the particle system.
  56958. */
  56959. ParticleSystem.prototype.rebuild = function () {
  56960. this._createIndexBuffer();
  56961. if (this._vertexBuffer) {
  56962. this._vertexBuffer._rebuild();
  56963. }
  56964. };
  56965. /**
  56966. * Is this system ready to be used/rendered
  56967. * @return true if the system is ready
  56968. */
  56969. ParticleSystem.prototype.isReady = function () {
  56970. var effect = this._getEffect();
  56971. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56972. return false;
  56973. }
  56974. return true;
  56975. };
  56976. /**
  56977. * Renders the particle system in its current state.
  56978. * @returns the current number of particles
  56979. */
  56980. ParticleSystem.prototype.render = function () {
  56981. var effect = this._getEffect();
  56982. // Check
  56983. if (!this.isReady() || !this._particles.length) {
  56984. return 0;
  56985. }
  56986. var engine = this._scene.getEngine();
  56987. // Render
  56988. engine.enableEffect(effect);
  56989. engine.setState(false);
  56990. var viewMatrix = this._scene.getViewMatrix();
  56991. effect.setTexture("diffuseSampler", this.particleTexture);
  56992. effect.setMatrix("view", viewMatrix);
  56993. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56994. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56995. var baseSize = this.particleTexture.getBaseSize();
  56996. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56997. }
  56998. effect.setVector2("translationPivot", this.translationPivot);
  56999. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57000. if (this._isBillboardBased) {
  57001. var camera = this._scene.activeCamera;
  57002. effect.setVector3("eyePosition", camera.globalPosition);
  57003. }
  57004. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57005. var invView = viewMatrix.clone();
  57006. invView.invert();
  57007. effect.setMatrix("invView", invView);
  57008. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57009. }
  57010. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57011. // image processing
  57012. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57013. this._imageProcessingConfiguration.bind(effect);
  57014. }
  57015. // Draw order
  57016. switch (this.blendMode) {
  57017. case ParticleSystem.BLENDMODE_ADD:
  57018. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57019. break;
  57020. case ParticleSystem.BLENDMODE_ONEONE:
  57021. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57022. break;
  57023. case ParticleSystem.BLENDMODE_STANDARD:
  57024. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57025. break;
  57026. }
  57027. if (this.forceDepthWrite) {
  57028. engine.setDepthWrite(true);
  57029. }
  57030. if (this._useInstancing) {
  57031. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57032. engine.unbindInstanceAttributes();
  57033. }
  57034. else {
  57035. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57036. }
  57037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57038. return this._particles.length;
  57039. };
  57040. /**
  57041. * Disposes the particle system and free the associated resources
  57042. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57043. */
  57044. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57045. if (disposeTexture === void 0) { disposeTexture = true; }
  57046. if (this._vertexBuffer) {
  57047. this._vertexBuffer.dispose();
  57048. this._vertexBuffer = null;
  57049. }
  57050. if (this._spriteBuffer) {
  57051. this._spriteBuffer.dispose();
  57052. this._spriteBuffer = null;
  57053. }
  57054. if (this._indexBuffer) {
  57055. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57056. this._indexBuffer = null;
  57057. }
  57058. if (disposeTexture && this.particleTexture) {
  57059. this.particleTexture.dispose();
  57060. this.particleTexture = null;
  57061. }
  57062. if (disposeTexture && this.noiseTexture) {
  57063. this.noiseTexture.dispose();
  57064. this.noiseTexture = null;
  57065. }
  57066. this._removeFromRoot();
  57067. // Remove from scene
  57068. var index = this._scene.particleSystems.indexOf(this);
  57069. if (index > -1) {
  57070. this._scene.particleSystems.splice(index, 1);
  57071. }
  57072. // Callback
  57073. this.onDisposeObservable.notifyObservers(this);
  57074. this.onDisposeObservable.clear();
  57075. };
  57076. // Clone
  57077. /**
  57078. * Clones the particle system.
  57079. * @param name The name of the cloned object
  57080. * @param newEmitter The new emitter to use
  57081. * @returns the cloned particle system
  57082. */
  57083. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57084. var custom = null;
  57085. var program = null;
  57086. if (this.customShader != null) {
  57087. program = this.customShader;
  57088. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57089. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57090. }
  57091. else if (this._customEffect) {
  57092. custom = this._customEffect;
  57093. }
  57094. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57095. result.customShader = program;
  57096. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57097. if (newEmitter === undefined) {
  57098. newEmitter = this.emitter;
  57099. }
  57100. result.emitter = newEmitter;
  57101. if (this.particleTexture) {
  57102. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57103. }
  57104. if (!this.preventAutoStart) {
  57105. result.start();
  57106. }
  57107. return result;
  57108. };
  57109. /**
  57110. * Serializes the particle system to a JSON object.
  57111. * @returns the JSON object
  57112. */
  57113. ParticleSystem.prototype.serialize = function () {
  57114. var serializationObject = {};
  57115. ParticleSystem._Serialize(serializationObject, this);
  57116. serializationObject.textureMask = this.textureMask.asArray();
  57117. serializationObject.customShader = this.customShader;
  57118. serializationObject.preventAutoStart = this.preventAutoStart;
  57119. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57120. return serializationObject;
  57121. };
  57122. /** @hidden */
  57123. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57124. serializationObject.name = particleSystem.name;
  57125. serializationObject.id = particleSystem.id;
  57126. serializationObject.capacity = particleSystem.getCapacity();
  57127. // Emitter
  57128. if (particleSystem.emitter.position) {
  57129. var emitterMesh = particleSystem.emitter;
  57130. serializationObject.emitterId = emitterMesh.id;
  57131. }
  57132. else {
  57133. var emitterPosition = particleSystem.emitter;
  57134. serializationObject.emitter = emitterPosition.asArray();
  57135. }
  57136. // Emitter
  57137. if (particleSystem.particleEmitterType) {
  57138. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57139. }
  57140. if (particleSystem.particleTexture) {
  57141. serializationObject.textureName = particleSystem.particleTexture.name;
  57142. }
  57143. // Animations
  57144. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57145. // Particle system
  57146. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57147. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57148. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57149. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57150. serializationObject.minSize = particleSystem.minSize;
  57151. serializationObject.maxSize = particleSystem.maxSize;
  57152. serializationObject.minScaleX = particleSystem.minScaleX;
  57153. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57154. serializationObject.minScaleY = particleSystem.minScaleY;
  57155. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57156. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57157. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57158. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57159. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57160. serializationObject.emitRate = particleSystem.emitRate;
  57161. serializationObject.gravity = particleSystem.gravity.asArray();
  57162. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57163. serializationObject.color1 = particleSystem.color1.asArray();
  57164. serializationObject.color2 = particleSystem.color2.asArray();
  57165. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57166. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57167. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57168. serializationObject.blendMode = particleSystem.blendMode;
  57169. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57170. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57171. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57172. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57173. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57174. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57175. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57176. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57177. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57178. var colorGradients = particleSystem.getColorGradients();
  57179. if (colorGradients) {
  57180. serializationObject.colorGradients = [];
  57181. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57182. var colorGradient = colorGradients_1[_i];
  57183. var serializedGradient = {
  57184. gradient: colorGradient.gradient,
  57185. color1: colorGradient.color1.asArray()
  57186. };
  57187. if (colorGradient.color2) {
  57188. serializedGradient.color2 = colorGradient.color2.asArray();
  57189. }
  57190. serializationObject.colorGradients.push(serializedGradient);
  57191. }
  57192. }
  57193. var sizeGradients = particleSystem.getSizeGradients();
  57194. if (sizeGradients) {
  57195. serializationObject.sizeGradients = [];
  57196. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57197. var sizeGradient = sizeGradients_1[_a];
  57198. var serializedGradient = {
  57199. gradient: sizeGradient.gradient,
  57200. factor1: sizeGradient.factor1
  57201. };
  57202. if (sizeGradient.factor2 !== undefined) {
  57203. serializedGradient.factor2 = sizeGradient.factor2;
  57204. }
  57205. serializationObject.sizeGradients.push(serializedGradient);
  57206. }
  57207. }
  57208. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57209. if (angularSpeedGradients) {
  57210. serializationObject.angularSpeedGradients = [];
  57211. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57212. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57213. var serializedGradient = {
  57214. gradient: angularSpeedGradient.gradient,
  57215. factor1: angularSpeedGradient.factor1
  57216. };
  57217. if (angularSpeedGradient.factor2 !== undefined) {
  57218. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57219. }
  57220. serializationObject.angularSpeedGradients.push(serializedGradient);
  57221. }
  57222. }
  57223. var velocityGradients = particleSystem.getVelocityGradients();
  57224. if (velocityGradients) {
  57225. serializationObject.velocityGradients = [];
  57226. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57227. var velocityGradient = velocityGradients_1[_c];
  57228. var serializedGradient = {
  57229. gradient: velocityGradient.gradient,
  57230. factor1: velocityGradient.factor1
  57231. };
  57232. if (velocityGradient.factor2 !== undefined) {
  57233. serializedGradient.factor2 = velocityGradient.factor2;
  57234. }
  57235. serializationObject.velocityGradients.push(serializedGradient);
  57236. }
  57237. }
  57238. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57239. if (limitVelocityGradients) {
  57240. serializationObject.limitVelocityGradients = [];
  57241. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  57242. var limitVelocityGradient = limitVelocityGradients_1[_d];
  57243. var serializedGradient = {
  57244. gradient: limitVelocityGradient.gradient,
  57245. factor1: limitVelocityGradient.factor1
  57246. };
  57247. if (limitVelocityGradient.factor2 !== undefined) {
  57248. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57249. }
  57250. serializationObject.limitVelocityGradients.push(serializedGradient);
  57251. }
  57252. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57253. }
  57254. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57255. var noiseTexture = particleSystem.noiseTexture;
  57256. serializationObject.noiseTexture = noiseTexture.serialize();
  57257. }
  57258. };
  57259. /** @hidden */
  57260. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57261. // Texture
  57262. if (parsedParticleSystem.textureName) {
  57263. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57264. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57265. }
  57266. // Emitter
  57267. if (parsedParticleSystem.emitterId === undefined) {
  57268. particleSystem.emitter = BABYLON.Vector3.Zero();
  57269. }
  57270. else if (parsedParticleSystem.emitterId) {
  57271. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57272. }
  57273. else {
  57274. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57275. }
  57276. // Misc.
  57277. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57278. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57279. }
  57280. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57281. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57282. }
  57283. // Animations
  57284. if (parsedParticleSystem.animations) {
  57285. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57286. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57287. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57288. }
  57289. }
  57290. if (parsedParticleSystem.autoAnimate) {
  57291. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57292. }
  57293. // Particle system
  57294. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57295. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57296. particleSystem.minSize = parsedParticleSystem.minSize;
  57297. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57298. if (parsedParticleSystem.minScaleX) {
  57299. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57300. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57301. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57302. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57303. }
  57304. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57305. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57306. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57307. }
  57308. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57309. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57310. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57311. }
  57312. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57313. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57314. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57315. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57316. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57317. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57318. if (parsedParticleSystem.noiseStrength) {
  57319. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57320. }
  57321. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57322. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57323. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57324. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57325. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57326. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57327. if (parsedParticleSystem.colorGradients) {
  57328. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57329. var colorGradient = _a[_i];
  57330. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57331. }
  57332. }
  57333. if (parsedParticleSystem.sizeGradients) {
  57334. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57335. var sizeGradient = _c[_b];
  57336. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57337. }
  57338. }
  57339. if (parsedParticleSystem.angularSpeedGradients) {
  57340. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57341. var angularSpeedGradient = _e[_d];
  57342. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57343. }
  57344. }
  57345. if (parsedParticleSystem.velocityGradients) {
  57346. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57347. var velocityGradient = _g[_f];
  57348. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57349. }
  57350. }
  57351. if (parsedParticleSystem.limitVelocityGradients) {
  57352. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  57353. var limitVelocityGradient = _j[_h];
  57354. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57355. }
  57356. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57357. }
  57358. if (parsedParticleSystem.noiseTexture) {
  57359. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57360. }
  57361. // Emitter
  57362. var emitterType;
  57363. if (parsedParticleSystem.particleEmitterType) {
  57364. switch (parsedParticleSystem.particleEmitterType.type) {
  57365. case "SphereParticleEmitter":
  57366. emitterType = new BABYLON.SphereParticleEmitter();
  57367. break;
  57368. case "SphereDirectedParticleEmitter":
  57369. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57370. break;
  57371. case "ConeEmitter":
  57372. case "ConeParticleEmitter":
  57373. emitterType = new BABYLON.ConeParticleEmitter();
  57374. break;
  57375. case "BoxEmitter":
  57376. case "BoxParticleEmitter":
  57377. default:
  57378. emitterType = new BABYLON.BoxParticleEmitter();
  57379. break;
  57380. }
  57381. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57382. }
  57383. else {
  57384. emitterType = new BABYLON.BoxParticleEmitter();
  57385. emitterType.parse(parsedParticleSystem);
  57386. }
  57387. particleSystem.particleEmitterType = emitterType;
  57388. // Animation sheet
  57389. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57390. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57391. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57392. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57393. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57394. };
  57395. /**
  57396. * Parses a JSON object to create a particle system.
  57397. * @param parsedParticleSystem The JSON object to parse
  57398. * @param scene The scene to create the particle system in
  57399. * @param rootUrl The root url to use to load external dependencies like texture
  57400. * @returns the Parsed particle system
  57401. */
  57402. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57403. var name = parsedParticleSystem.name;
  57404. var custom = null;
  57405. var program = null;
  57406. if (parsedParticleSystem.customShader) {
  57407. program = parsedParticleSystem.customShader;
  57408. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57409. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57410. }
  57411. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57412. particleSystem.customShader = program;
  57413. if (parsedParticleSystem.id) {
  57414. particleSystem.id = parsedParticleSystem.id;
  57415. }
  57416. // Auto start
  57417. if (parsedParticleSystem.preventAutoStart) {
  57418. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57419. }
  57420. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57421. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57422. if (!particleSystem.preventAutoStart) {
  57423. particleSystem.start();
  57424. }
  57425. return particleSystem;
  57426. };
  57427. return ParticleSystem;
  57428. }(BABYLON.BaseParticleSystem));
  57429. BABYLON.ParticleSystem = ParticleSystem;
  57430. })(BABYLON || (BABYLON = {}));
  57431. //# sourceMappingURL=babylon.particleSystem.js.map
  57432. var BABYLON;
  57433. (function (BABYLON) {
  57434. /**
  57435. * Particle emitter emitting particles from the inside of a box.
  57436. * It emits the particles randomly between 2 given directions.
  57437. */
  57438. var BoxParticleEmitter = /** @class */ (function () {
  57439. /**
  57440. * Creates a new instance BoxParticleEmitter
  57441. */
  57442. function BoxParticleEmitter() {
  57443. /**
  57444. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57445. */
  57446. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57447. /**
  57448. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57449. */
  57450. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57451. /**
  57452. * 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.
  57453. */
  57454. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57455. /**
  57456. * 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.
  57457. */
  57458. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57459. }
  57460. /**
  57461. * Called by the particle System when the direction is computed for the created particle.
  57462. * @param worldMatrix is the world matrix of the particle system
  57463. * @param directionToUpdate is the direction vector to update with the result
  57464. * @param particle is the particle we are computed the direction for
  57465. */
  57466. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57467. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57468. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57469. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57470. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57471. };
  57472. /**
  57473. * Called by the particle System when the position is computed for the created particle.
  57474. * @param worldMatrix is the world matrix of the particle system
  57475. * @param positionToUpdate is the position vector to update with the result
  57476. * @param particle is the particle we are computed the position for
  57477. */
  57478. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57479. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57480. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57481. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57482. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57483. };
  57484. /**
  57485. * Clones the current emitter and returns a copy of it
  57486. * @returns the new emitter
  57487. */
  57488. BoxParticleEmitter.prototype.clone = function () {
  57489. var newOne = new BoxParticleEmitter();
  57490. BABYLON.Tools.DeepCopy(this, newOne);
  57491. return newOne;
  57492. };
  57493. /**
  57494. * Called by the GPUParticleSystem to setup the update shader
  57495. * @param effect defines the update shader
  57496. */
  57497. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57498. effect.setVector3("direction1", this.direction1);
  57499. effect.setVector3("direction2", this.direction2);
  57500. effect.setVector3("minEmitBox", this.minEmitBox);
  57501. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57502. };
  57503. /**
  57504. * Returns a string to use to update the GPU particles update shader
  57505. * @returns a string containng the defines string
  57506. */
  57507. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57508. return "#define BOXEMITTER";
  57509. };
  57510. /**
  57511. * Returns the string "BoxParticleEmitter"
  57512. * @returns a string containing the class name
  57513. */
  57514. BoxParticleEmitter.prototype.getClassName = function () {
  57515. return "BoxParticleEmitter";
  57516. };
  57517. /**
  57518. * Serializes the particle system to a JSON object.
  57519. * @returns the JSON object
  57520. */
  57521. BoxParticleEmitter.prototype.serialize = function () {
  57522. var serializationObject = {};
  57523. serializationObject.type = this.getClassName();
  57524. serializationObject.direction1 = this.direction1.asArray();
  57525. serializationObject.direction2 = this.direction2.asArray();
  57526. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57527. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57528. return serializationObject;
  57529. };
  57530. /**
  57531. * Parse properties from a JSON object
  57532. * @param serializationObject defines the JSON object
  57533. */
  57534. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57535. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57536. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57537. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57538. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57539. };
  57540. return BoxParticleEmitter;
  57541. }());
  57542. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57543. })(BABYLON || (BABYLON = {}));
  57544. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57545. var BABYLON;
  57546. (function (BABYLON) {
  57547. /**
  57548. * Particle emitter emitting particles from the inside of a cone.
  57549. * It emits the particles alongside the cone volume from the base to the particle.
  57550. * The emission direction might be randomized.
  57551. */
  57552. var ConeParticleEmitter = /** @class */ (function () {
  57553. /**
  57554. * Creates a new instance ConeParticleEmitter
  57555. * @param radius the radius of the emission cone (1 by default)
  57556. * @param angles the cone base angle (PI by default)
  57557. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57558. */
  57559. function ConeParticleEmitter(radius, angle,
  57560. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57561. directionRandomizer) {
  57562. if (radius === void 0) { radius = 1; }
  57563. if (angle === void 0) { angle = Math.PI; }
  57564. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57565. this.directionRandomizer = directionRandomizer;
  57566. /**
  57567. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57568. */
  57569. this.radiusRange = 1;
  57570. /**
  57571. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57572. */
  57573. this.heightRange = 1;
  57574. /**
  57575. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57576. */
  57577. this.emitFromSpawnPointOnly = false;
  57578. this.angle = angle;
  57579. this.radius = radius;
  57580. }
  57581. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57582. /**
  57583. * Gets or sets the radius of the emission cone
  57584. */
  57585. get: function () {
  57586. return this._radius;
  57587. },
  57588. set: function (value) {
  57589. this._radius = value;
  57590. this._buildHeight();
  57591. },
  57592. enumerable: true,
  57593. configurable: true
  57594. });
  57595. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57596. /**
  57597. * Gets or sets the angle of the emission cone
  57598. */
  57599. get: function () {
  57600. return this._angle;
  57601. },
  57602. set: function (value) {
  57603. this._angle = value;
  57604. this._buildHeight();
  57605. },
  57606. enumerable: true,
  57607. configurable: true
  57608. });
  57609. ConeParticleEmitter.prototype._buildHeight = function () {
  57610. if (this._angle !== 0) {
  57611. this._height = this._radius / Math.tan(this._angle / 2);
  57612. }
  57613. else {
  57614. this._height = 1;
  57615. }
  57616. };
  57617. /**
  57618. * Called by the particle System when the direction is computed for the created particle.
  57619. * @param worldMatrix is the world matrix of the particle system
  57620. * @param directionToUpdate is the direction vector to update with the result
  57621. * @param particle is the particle we are computed the direction for
  57622. */
  57623. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57624. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57625. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57626. }
  57627. else {
  57628. // measure the direction Vector from the emitter to the particle.
  57629. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57630. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57631. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57632. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57633. direction.x += randX;
  57634. direction.y += randY;
  57635. direction.z += randZ;
  57636. direction.normalize();
  57637. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57638. }
  57639. };
  57640. /**
  57641. * Called by the particle System when the position is computed for the created particle.
  57642. * @param worldMatrix is the world matrix of the particle system
  57643. * @param positionToUpdate is the position vector to update with the result
  57644. * @param particle is the particle we are computed the position for
  57645. */
  57646. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57647. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57648. var h;
  57649. if (!this.emitFromSpawnPointOnly) {
  57650. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57651. // Better distribution in a cone at normal angles.
  57652. h = 1 - h * h;
  57653. }
  57654. else {
  57655. h = 0.0001;
  57656. }
  57657. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57658. radius = radius * h;
  57659. var randX = radius * Math.sin(s);
  57660. var randZ = radius * Math.cos(s);
  57661. var randY = h * this._height;
  57662. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57663. };
  57664. /**
  57665. * Clones the current emitter and returns a copy of it
  57666. * @returns the new emitter
  57667. */
  57668. ConeParticleEmitter.prototype.clone = function () {
  57669. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57670. BABYLON.Tools.DeepCopy(this, newOne);
  57671. return newOne;
  57672. };
  57673. /**
  57674. * Called by the GPUParticleSystem to setup the update shader
  57675. * @param effect defines the update shader
  57676. */
  57677. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57678. effect.setFloat2("radius", this._radius, this.radiusRange);
  57679. effect.setFloat("coneAngle", this._angle);
  57680. effect.setFloat2("height", this._height, this.heightRange);
  57681. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57682. };
  57683. /**
  57684. * Returns a string to use to update the GPU particles update shader
  57685. * @returns a string containng the defines string
  57686. */
  57687. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57688. var defines = "#define CONEEMITTER";
  57689. if (this.emitFromSpawnPointOnly) {
  57690. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57691. }
  57692. return defines;
  57693. };
  57694. /**
  57695. * Returns the string "ConeParticleEmitter"
  57696. * @returns a string containing the class name
  57697. */
  57698. ConeParticleEmitter.prototype.getClassName = function () {
  57699. return "ConeParticleEmitter";
  57700. };
  57701. /**
  57702. * Serializes the particle system to a JSON object.
  57703. * @returns the JSON object
  57704. */
  57705. ConeParticleEmitter.prototype.serialize = function () {
  57706. var serializationObject = {};
  57707. serializationObject.type = this.getClassName();
  57708. serializationObject.radius = this._radius;
  57709. serializationObject.angle = this._angle;
  57710. serializationObject.directionRandomizer = this.directionRandomizer;
  57711. return serializationObject;
  57712. };
  57713. /**
  57714. * Parse properties from a JSON object
  57715. * @param serializationObject defines the JSON object
  57716. */
  57717. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57718. this.radius = serializationObject.radius;
  57719. this.angle = serializationObject.angle;
  57720. this.directionRandomizer = serializationObject.directionRandomizer;
  57721. };
  57722. return ConeParticleEmitter;
  57723. }());
  57724. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57725. })(BABYLON || (BABYLON = {}));
  57726. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57727. var BABYLON;
  57728. (function (BABYLON) {
  57729. /**
  57730. * Particle emitter emitting particles from the inside of a sphere.
  57731. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57732. */
  57733. var SphereParticleEmitter = /** @class */ (function () {
  57734. /**
  57735. * Creates a new instance SphereParticleEmitter
  57736. * @param radius the radius of the emission sphere (1 by default)
  57737. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57738. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57739. */
  57740. function SphereParticleEmitter(
  57741. /**
  57742. * The radius of the emission sphere.
  57743. */
  57744. radius,
  57745. /**
  57746. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57747. */
  57748. radiusRange,
  57749. /**
  57750. * How much to randomize the particle direction [0-1].
  57751. */
  57752. directionRandomizer) {
  57753. if (radius === void 0) { radius = 1; }
  57754. if (radiusRange === void 0) { radiusRange = 1; }
  57755. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57756. this.radius = radius;
  57757. this.radiusRange = radiusRange;
  57758. this.directionRandomizer = directionRandomizer;
  57759. }
  57760. /**
  57761. * Called by the particle System when the direction is computed for the created particle.
  57762. * @param worldMatrix is the world matrix of the particle system
  57763. * @param directionToUpdate is the direction vector to update with the result
  57764. * @param particle is the particle we are computed the direction for
  57765. */
  57766. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57767. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57768. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57769. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57770. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57771. direction.x += randX;
  57772. direction.y += randY;
  57773. direction.z += randZ;
  57774. direction.normalize();
  57775. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57776. };
  57777. /**
  57778. * Called by the particle System when the position is computed for the created particle.
  57779. * @param worldMatrix is the world matrix of the particle system
  57780. * @param positionToUpdate is the position vector to update with the result
  57781. * @param particle is the particle we are computed the position for
  57782. */
  57783. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57784. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57785. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57786. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57787. var theta = Math.acos(2 * v - 1);
  57788. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57789. var randY = randRadius * Math.cos(theta);
  57790. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57791. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57792. };
  57793. /**
  57794. * Clones the current emitter and returns a copy of it
  57795. * @returns the new emitter
  57796. */
  57797. SphereParticleEmitter.prototype.clone = function () {
  57798. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57799. BABYLON.Tools.DeepCopy(this, newOne);
  57800. return newOne;
  57801. };
  57802. /**
  57803. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57804. * @param effect defines the update shader
  57805. */
  57806. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57807. effect.setFloat("radius", this.radius);
  57808. effect.setFloat("radiusRange", this.radiusRange);
  57809. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57810. };
  57811. /**
  57812. * Returns a string to use to update the GPU particles update shader
  57813. * @returns a string containng the defines string
  57814. */
  57815. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57816. return "#define SPHEREEMITTER";
  57817. };
  57818. /**
  57819. * Returns the string "SphereParticleEmitter"
  57820. * @returns a string containing the class name
  57821. */
  57822. SphereParticleEmitter.prototype.getClassName = function () {
  57823. return "SphereParticleEmitter";
  57824. };
  57825. /**
  57826. * Serializes the particle system to a JSON object.
  57827. * @returns the JSON object
  57828. */
  57829. SphereParticleEmitter.prototype.serialize = function () {
  57830. var serializationObject = {};
  57831. serializationObject.type = this.getClassName();
  57832. serializationObject.radius = this.radius;
  57833. serializationObject.radiusRange = this.radiusRange;
  57834. serializationObject.directionRandomizer = this.directionRandomizer;
  57835. return serializationObject;
  57836. };
  57837. /**
  57838. * Parse properties from a JSON object
  57839. * @param serializationObject defines the JSON object
  57840. */
  57841. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57842. this.radius = serializationObject.radius;
  57843. this.radiusRange = serializationObject.radiusRange;
  57844. this.directionRandomizer = serializationObject.directionRandomizer;
  57845. };
  57846. return SphereParticleEmitter;
  57847. }());
  57848. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57849. /**
  57850. * Particle emitter emitting particles from the inside of a sphere.
  57851. * It emits the particles randomly between two vectors.
  57852. */
  57853. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57854. __extends(SphereDirectedParticleEmitter, _super);
  57855. /**
  57856. * Creates a new instance SphereDirectedParticleEmitter
  57857. * @param radius the radius of the emission sphere (1 by default)
  57858. * @param direction1 the min limit of the emission direction (up vector by default)
  57859. * @param direction2 the max limit of the emission direction (up vector by default)
  57860. */
  57861. function SphereDirectedParticleEmitter(radius,
  57862. /**
  57863. * The min limit of the emission direction.
  57864. */
  57865. direction1,
  57866. /**
  57867. * The max limit of the emission direction.
  57868. */
  57869. direction2) {
  57870. if (radius === void 0) { radius = 1; }
  57871. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57872. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57873. var _this = _super.call(this, radius) || this;
  57874. _this.direction1 = direction1;
  57875. _this.direction2 = direction2;
  57876. return _this;
  57877. }
  57878. /**
  57879. * Called by the particle System when the direction is computed for the created particle.
  57880. * @param worldMatrix is the world matrix of the particle system
  57881. * @param directionToUpdate is the direction vector to update with the result
  57882. * @param particle is the particle we are computed the direction for
  57883. */
  57884. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57885. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57886. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57887. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57888. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57889. };
  57890. /**
  57891. * Clones the current emitter and returns a copy of it
  57892. * @returns the new emitter
  57893. */
  57894. SphereDirectedParticleEmitter.prototype.clone = function () {
  57895. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57896. BABYLON.Tools.DeepCopy(this, newOne);
  57897. return newOne;
  57898. };
  57899. /**
  57900. * Called by the GPUParticleSystem to setup the update shader
  57901. * @param effect defines the update shader
  57902. */
  57903. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57904. effect.setFloat("radius", this.radius);
  57905. effect.setFloat("radiusRange", this.radiusRange);
  57906. effect.setVector3("direction1", this.direction1);
  57907. effect.setVector3("direction2", this.direction2);
  57908. };
  57909. /**
  57910. * Returns a string to use to update the GPU particles update shader
  57911. * @returns a string containng the defines string
  57912. */
  57913. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57914. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57915. };
  57916. /**
  57917. * Returns the string "SphereDirectedParticleEmitter"
  57918. * @returns a string containing the class name
  57919. */
  57920. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57921. return "SphereDirectedParticleEmitter";
  57922. };
  57923. /**
  57924. * Serializes the particle system to a JSON object.
  57925. * @returns the JSON object
  57926. */
  57927. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57928. var serializationObject = _super.prototype.serialize.call(this);
  57929. serializationObject.direction1 = this.direction1.asArray();
  57930. serializationObject.direction2 = this.direction2.asArray();
  57931. return serializationObject;
  57932. };
  57933. /**
  57934. * Parse properties from a JSON object
  57935. * @param serializationObject defines the JSON object
  57936. */
  57937. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57938. _super.prototype.parse.call(this, serializationObject);
  57939. this.direction1.copyFrom(serializationObject.direction1);
  57940. this.direction2.copyFrom(serializationObject.direction2);
  57941. };
  57942. return SphereDirectedParticleEmitter;
  57943. }(SphereParticleEmitter));
  57944. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57945. })(BABYLON || (BABYLON = {}));
  57946. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57947. var BABYLON;
  57948. (function (BABYLON) {
  57949. /**
  57950. * Particle emitter emitting particles from the inside of a hemisphere.
  57951. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  57952. */
  57953. var HemisphericParticleEmitter = /** @class */ (function () {
  57954. /**
  57955. * Creates a new instance HemisphericParticleEmitter
  57956. * @param radius the radius of the emission hemisphere (1 by default)
  57957. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57958. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57959. */
  57960. function HemisphericParticleEmitter(
  57961. /**
  57962. * The radius of the emission hemisphere.
  57963. */
  57964. radius,
  57965. /**
  57966. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57967. */
  57968. radiusRange,
  57969. /**
  57970. * How much to randomize the particle direction [0-1].
  57971. */
  57972. directionRandomizer) {
  57973. if (radius === void 0) { radius = 1; }
  57974. if (radiusRange === void 0) { radiusRange = 1; }
  57975. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57976. this.radius = radius;
  57977. this.radiusRange = radiusRange;
  57978. this.directionRandomizer = directionRandomizer;
  57979. }
  57980. /**
  57981. * Called by the particle System when the direction is computed for the created particle.
  57982. * @param worldMatrix is the world matrix of the particle system
  57983. * @param directionToUpdate is the direction vector to update with the result
  57984. * @param particle is the particle we are computed the direction for
  57985. */
  57986. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57987. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57988. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57989. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57990. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57991. direction.x += randX;
  57992. direction.y += randY;
  57993. direction.z += randZ;
  57994. direction.normalize();
  57995. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57996. };
  57997. /**
  57998. * Called by the particle System when the position is computed for the created particle.
  57999. * @param worldMatrix is the world matrix of the particle system
  58000. * @param positionToUpdate is the position vector to update with the result
  58001. * @param particle is the particle we are computed the position for
  58002. */
  58003. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58004. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58005. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58006. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58007. var theta = Math.acos(2 * v - 1);
  58008. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58009. var randY = randRadius * Math.cos(theta);
  58010. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58011. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58012. };
  58013. /**
  58014. * Clones the current emitter and returns a copy of it
  58015. * @returns the new emitter
  58016. */
  58017. HemisphericParticleEmitter.prototype.clone = function () {
  58018. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58019. BABYLON.Tools.DeepCopy(this, newOne);
  58020. return newOne;
  58021. };
  58022. /**
  58023. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58024. * @param effect defines the update shader
  58025. */
  58026. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58027. effect.setFloat("radius", this.radius);
  58028. effect.setFloat("radiusRange", this.radiusRange);
  58029. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58030. };
  58031. /**
  58032. * Returns a string to use to update the GPU particles update shader
  58033. * @returns a string containng the defines string
  58034. */
  58035. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58036. return "#define HEMISPHERICEMITTER";
  58037. };
  58038. /**
  58039. * Returns the string "HemisphericParticleEmitter"
  58040. * @returns a string containing the class name
  58041. */
  58042. HemisphericParticleEmitter.prototype.getClassName = function () {
  58043. return "HemisphericParticleEmitter";
  58044. };
  58045. /**
  58046. * Serializes the particle system to a JSON object.
  58047. * @returns the JSON object
  58048. */
  58049. HemisphericParticleEmitter.prototype.serialize = function () {
  58050. var serializationObject = {};
  58051. serializationObject.type = this.getClassName();
  58052. serializationObject.radius = this.radius;
  58053. serializationObject.radiusRange = this.radiusRange;
  58054. serializationObject.directionRandomizer = this.directionRandomizer;
  58055. return serializationObject;
  58056. };
  58057. /**
  58058. * Parse properties from a JSON object
  58059. * @param serializationObject defines the JSON object
  58060. */
  58061. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58062. this.radius = serializationObject.radius;
  58063. this.radiusRange = serializationObject.radiusRange;
  58064. this.directionRandomizer = serializationObject.directionRandomizer;
  58065. };
  58066. return HemisphericParticleEmitter;
  58067. }());
  58068. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58069. })(BABYLON || (BABYLON = {}));
  58070. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58071. var BABYLON;
  58072. (function (BABYLON) {
  58073. /**
  58074. * Particle emitter emitting particles from a point.
  58075. * It emits the particles randomly between 2 given directions.
  58076. */
  58077. var PointParticleEmitter = /** @class */ (function () {
  58078. /**
  58079. * Creates a new instance PointParticleEmitter
  58080. */
  58081. function PointParticleEmitter() {
  58082. /**
  58083. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58084. */
  58085. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58086. /**
  58087. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58088. */
  58089. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58090. }
  58091. /**
  58092. * Called by the particle System when the direction is computed for the created particle.
  58093. * @param worldMatrix is the world matrix of the particle system
  58094. * @param directionToUpdate is the direction vector to update with the result
  58095. * @param particle is the particle we are computed the direction for
  58096. */
  58097. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58098. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58099. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58100. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58101. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58102. };
  58103. /**
  58104. * Called by the particle System when the position is computed for the created particle.
  58105. * @param worldMatrix is the world matrix of the particle system
  58106. * @param positionToUpdate is the position vector to update with the result
  58107. * @param particle is the particle we are computed the position for
  58108. */
  58109. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58111. };
  58112. /**
  58113. * Clones the current emitter and returns a copy of it
  58114. * @returns the new emitter
  58115. */
  58116. PointParticleEmitter.prototype.clone = function () {
  58117. var newOne = new PointParticleEmitter();
  58118. BABYLON.Tools.DeepCopy(this, newOne);
  58119. return newOne;
  58120. };
  58121. /**
  58122. * Called by the GPUParticleSystem to setup the update shader
  58123. * @param effect defines the update shader
  58124. */
  58125. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58126. effect.setVector3("direction1", this.direction1);
  58127. effect.setVector3("direction2", this.direction2);
  58128. };
  58129. /**
  58130. * Returns a string to use to update the GPU particles update shader
  58131. * @returns a string containng the defines string
  58132. */
  58133. PointParticleEmitter.prototype.getEffectDefines = function () {
  58134. return "#define POINTEMITTER";
  58135. };
  58136. /**
  58137. * Returns the string "PointParticleEmitter"
  58138. * @returns a string containing the class name
  58139. */
  58140. PointParticleEmitter.prototype.getClassName = function () {
  58141. return "PointParticleEmitter";
  58142. };
  58143. /**
  58144. * Serializes the particle system to a JSON object.
  58145. * @returns the JSON object
  58146. */
  58147. PointParticleEmitter.prototype.serialize = function () {
  58148. var serializationObject = {};
  58149. serializationObject.type = this.getClassName();
  58150. serializationObject.direction1 = this.direction1.asArray();
  58151. serializationObject.direction2 = this.direction2.asArray();
  58152. return serializationObject;
  58153. };
  58154. /**
  58155. * Parse properties from a JSON object
  58156. * @param serializationObject defines the JSON object
  58157. */
  58158. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58159. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58160. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58161. };
  58162. return PointParticleEmitter;
  58163. }());
  58164. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58165. })(BABYLON || (BABYLON = {}));
  58166. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58167. var BABYLON;
  58168. (function (BABYLON) {
  58169. // Adds the parsers to the scene parsers.
  58170. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58171. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58172. if (!individualParser) {
  58173. return;
  58174. }
  58175. // Particles Systems
  58176. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58177. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58178. var parsedParticleSystem = parsedData.particleSystems[index];
  58179. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58180. }
  58181. }
  58182. });
  58183. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58184. if (parsedParticleSystem.activeParticleCount) {
  58185. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58186. return ps;
  58187. }
  58188. else {
  58189. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58190. return ps;
  58191. }
  58192. });
  58193. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58194. if (uniformsNames === void 0) { uniformsNames = []; }
  58195. if (samplers === void 0) { samplers = []; }
  58196. if (defines === void 0) { defines = ""; }
  58197. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58198. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58199. if (defines.indexOf(" BILLBOARD") === -1) {
  58200. defines += "\n#define BILLBOARD\n";
  58201. }
  58202. if (samplers.indexOf("diffuseSampler") === -1) {
  58203. samplers.push("diffuseSampler");
  58204. }
  58205. return this.createEffect({
  58206. vertex: "particles",
  58207. fragmentElement: fragmentName
  58208. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58209. };
  58210. })(BABYLON || (BABYLON = {}));
  58211. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58212. var BABYLON;
  58213. (function (BABYLON) {
  58214. var ShaderMaterial = /** @class */ (function (_super) {
  58215. __extends(ShaderMaterial, _super);
  58216. function ShaderMaterial(name, scene, shaderPath, options) {
  58217. var _this = _super.call(this, name, scene) || this;
  58218. _this._textures = {};
  58219. _this._textureArrays = {};
  58220. _this._floats = {};
  58221. _this._ints = {};
  58222. _this._floatsArrays = {};
  58223. _this._colors3 = {};
  58224. _this._colors3Arrays = {};
  58225. _this._colors4 = {};
  58226. _this._vectors2 = {};
  58227. _this._vectors3 = {};
  58228. _this._vectors4 = {};
  58229. _this._matrices = {};
  58230. _this._matrices3x3 = {};
  58231. _this._matrices2x2 = {};
  58232. _this._vectors2Arrays = {};
  58233. _this._vectors3Arrays = {};
  58234. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58235. _this._shaderPath = shaderPath;
  58236. options.needAlphaBlending = options.needAlphaBlending || false;
  58237. options.needAlphaTesting = options.needAlphaTesting || false;
  58238. options.attributes = options.attributes || ["position", "normal", "uv"];
  58239. options.uniforms = options.uniforms || ["worldViewProjection"];
  58240. options.uniformBuffers = options.uniformBuffers || [];
  58241. options.samplers = options.samplers || [];
  58242. options.defines = options.defines || [];
  58243. _this._options = options;
  58244. return _this;
  58245. }
  58246. ShaderMaterial.prototype.getClassName = function () {
  58247. return "ShaderMaterial";
  58248. };
  58249. ShaderMaterial.prototype.needAlphaBlending = function () {
  58250. return this._options.needAlphaBlending;
  58251. };
  58252. ShaderMaterial.prototype.needAlphaTesting = function () {
  58253. return this._options.needAlphaTesting;
  58254. };
  58255. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58256. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58257. this._options.uniforms.push(uniformName);
  58258. }
  58259. };
  58260. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58261. if (this._options.samplers.indexOf(name) === -1) {
  58262. this._options.samplers.push(name);
  58263. }
  58264. this._textures[name] = texture;
  58265. return this;
  58266. };
  58267. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58268. if (this._options.samplers.indexOf(name) === -1) {
  58269. this._options.samplers.push(name);
  58270. }
  58271. this._checkUniform(name);
  58272. this._textureArrays[name] = textures;
  58273. return this;
  58274. };
  58275. ShaderMaterial.prototype.setFloat = function (name, value) {
  58276. this._checkUniform(name);
  58277. this._floats[name] = value;
  58278. return this;
  58279. };
  58280. ShaderMaterial.prototype.setInt = function (name, value) {
  58281. this._checkUniform(name);
  58282. this._ints[name] = value;
  58283. return this;
  58284. };
  58285. ShaderMaterial.prototype.setFloats = function (name, value) {
  58286. this._checkUniform(name);
  58287. this._floatsArrays[name] = value;
  58288. return this;
  58289. };
  58290. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58291. this._checkUniform(name);
  58292. this._colors3[name] = value;
  58293. return this;
  58294. };
  58295. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58296. this._checkUniform(name);
  58297. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58298. color.toArray(arr, arr.length);
  58299. return arr;
  58300. }, []);
  58301. return this;
  58302. };
  58303. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58304. this._checkUniform(name);
  58305. this._colors4[name] = value;
  58306. return this;
  58307. };
  58308. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58309. this._checkUniform(name);
  58310. this._vectors2[name] = value;
  58311. return this;
  58312. };
  58313. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58314. this._checkUniform(name);
  58315. this._vectors3[name] = value;
  58316. return this;
  58317. };
  58318. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58319. this._checkUniform(name);
  58320. this._vectors4[name] = value;
  58321. return this;
  58322. };
  58323. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58324. this._checkUniform(name);
  58325. this._matrices[name] = value;
  58326. return this;
  58327. };
  58328. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58329. this._checkUniform(name);
  58330. this._matrices3x3[name] = value;
  58331. return this;
  58332. };
  58333. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58334. this._checkUniform(name);
  58335. this._matrices2x2[name] = value;
  58336. return this;
  58337. };
  58338. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58339. this._checkUniform(name);
  58340. this._vectors2Arrays[name] = value;
  58341. return this;
  58342. };
  58343. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58344. this._checkUniform(name);
  58345. this._vectors3Arrays[name] = value;
  58346. return this;
  58347. };
  58348. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58349. if (!mesh) {
  58350. return true;
  58351. }
  58352. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58353. return false;
  58354. }
  58355. return false;
  58356. };
  58357. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58358. var scene = this.getScene();
  58359. var engine = scene.getEngine();
  58360. if (!this.checkReadyOnEveryCall) {
  58361. if (this._renderId === scene.getRenderId()) {
  58362. if (this._checkCache(scene, mesh, useInstances)) {
  58363. return true;
  58364. }
  58365. }
  58366. }
  58367. // Instances
  58368. var defines = [];
  58369. var attribs = [];
  58370. var fallbacks = new BABYLON.EffectFallbacks();
  58371. if (useInstances) {
  58372. defines.push("#define INSTANCES");
  58373. }
  58374. for (var index = 0; index < this._options.defines.length; index++) {
  58375. defines.push(this._options.defines[index]);
  58376. }
  58377. for (var index = 0; index < this._options.attributes.length; index++) {
  58378. attribs.push(this._options.attributes[index]);
  58379. }
  58380. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58381. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58382. defines.push("#define VERTEXCOLOR");
  58383. }
  58384. // Bones
  58385. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58388. if (mesh.numBoneInfluencers > 4) {
  58389. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58390. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58391. }
  58392. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58393. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58394. fallbacks.addCPUSkinningFallback(0, mesh);
  58395. if (this._options.uniforms.indexOf("mBones") === -1) {
  58396. this._options.uniforms.push("mBones");
  58397. }
  58398. }
  58399. else {
  58400. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58401. }
  58402. // Textures
  58403. for (var name in this._textures) {
  58404. if (!this._textures[name].isReady()) {
  58405. return false;
  58406. }
  58407. }
  58408. // Alpha test
  58409. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58410. defines.push("#define ALPHATEST");
  58411. }
  58412. var previousEffect = this._effect;
  58413. var join = defines.join("\n");
  58414. this._effect = engine.createEffect(this._shaderPath, {
  58415. attributes: attribs,
  58416. uniformsNames: this._options.uniforms,
  58417. uniformBuffersNames: this._options.uniformBuffers,
  58418. samplers: this._options.samplers,
  58419. defines: join,
  58420. fallbacks: fallbacks,
  58421. onCompiled: this.onCompiled,
  58422. onError: this.onError
  58423. }, engine);
  58424. if (!this._effect.isReady()) {
  58425. return false;
  58426. }
  58427. if (previousEffect !== this._effect) {
  58428. scene.resetCachedMaterial();
  58429. }
  58430. this._renderId = scene.getRenderId();
  58431. return true;
  58432. };
  58433. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58434. var scene = this.getScene();
  58435. if (!this._effect) {
  58436. return;
  58437. }
  58438. if (this._options.uniforms.indexOf("world") !== -1) {
  58439. this._effect.setMatrix("world", world);
  58440. }
  58441. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58442. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58443. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58444. }
  58445. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58446. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58447. }
  58448. };
  58449. ShaderMaterial.prototype.bind = function (world, mesh) {
  58450. // Std values
  58451. this.bindOnlyWorldMatrix(world);
  58452. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58453. if (this._options.uniforms.indexOf("view") !== -1) {
  58454. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58455. }
  58456. if (this._options.uniforms.indexOf("projection") !== -1) {
  58457. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58458. }
  58459. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58460. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58461. }
  58462. // Bones
  58463. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58464. var name;
  58465. // Texture
  58466. for (name in this._textures) {
  58467. this._effect.setTexture(name, this._textures[name]);
  58468. }
  58469. // Texture arrays
  58470. for (name in this._textureArrays) {
  58471. this._effect.setTextureArray(name, this._textureArrays[name]);
  58472. }
  58473. // Int
  58474. for (name in this._ints) {
  58475. this._effect.setInt(name, this._ints[name]);
  58476. }
  58477. // Float
  58478. for (name in this._floats) {
  58479. this._effect.setFloat(name, this._floats[name]);
  58480. }
  58481. // Floats
  58482. for (name in this._floatsArrays) {
  58483. this._effect.setArray(name, this._floatsArrays[name]);
  58484. }
  58485. // Color3
  58486. for (name in this._colors3) {
  58487. this._effect.setColor3(name, this._colors3[name]);
  58488. }
  58489. for (name in this._colors3Arrays) {
  58490. this._effect.setArray3(name, this._colors3Arrays[name]);
  58491. }
  58492. // Color4
  58493. for (name in this._colors4) {
  58494. var color = this._colors4[name];
  58495. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58496. }
  58497. // Vector2
  58498. for (name in this._vectors2) {
  58499. this._effect.setVector2(name, this._vectors2[name]);
  58500. }
  58501. // Vector3
  58502. for (name in this._vectors3) {
  58503. this._effect.setVector3(name, this._vectors3[name]);
  58504. }
  58505. // Vector4
  58506. for (name in this._vectors4) {
  58507. this._effect.setVector4(name, this._vectors4[name]);
  58508. }
  58509. // Matrix
  58510. for (name in this._matrices) {
  58511. this._effect.setMatrix(name, this._matrices[name]);
  58512. }
  58513. // Matrix 3x3
  58514. for (name in this._matrices3x3) {
  58515. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58516. }
  58517. // Matrix 2x2
  58518. for (name in this._matrices2x2) {
  58519. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58520. }
  58521. // Vector2Array
  58522. for (name in this._vectors2Arrays) {
  58523. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58524. }
  58525. // Vector3Array
  58526. for (name in this._vectors3Arrays) {
  58527. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58528. }
  58529. }
  58530. this._afterBind(mesh);
  58531. };
  58532. ShaderMaterial.prototype.getActiveTextures = function () {
  58533. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58534. for (var name in this._textures) {
  58535. activeTextures.push(this._textures[name]);
  58536. }
  58537. for (var name in this._textureArrays) {
  58538. var array = this._textureArrays[name];
  58539. for (var index = 0; index < array.length; index++) {
  58540. activeTextures.push(array[index]);
  58541. }
  58542. }
  58543. return activeTextures;
  58544. };
  58545. ShaderMaterial.prototype.hasTexture = function (texture) {
  58546. if (_super.prototype.hasTexture.call(this, texture)) {
  58547. return true;
  58548. }
  58549. for (var name in this._textures) {
  58550. if (this._textures[name] === texture) {
  58551. return true;
  58552. }
  58553. }
  58554. for (var name in this._textureArrays) {
  58555. var array = this._textureArrays[name];
  58556. for (var index = 0; index < array.length; index++) {
  58557. if (array[index] === texture) {
  58558. return true;
  58559. }
  58560. }
  58561. }
  58562. return false;
  58563. };
  58564. ShaderMaterial.prototype.clone = function (name) {
  58565. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58566. return newShaderMaterial;
  58567. };
  58568. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58569. if (forceDisposeTextures) {
  58570. var name;
  58571. for (name in this._textures) {
  58572. this._textures[name].dispose();
  58573. }
  58574. for (name in this._textureArrays) {
  58575. var array = this._textureArrays[name];
  58576. for (var index = 0; index < array.length; index++) {
  58577. array[index].dispose();
  58578. }
  58579. }
  58580. }
  58581. this._textures = {};
  58582. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58583. };
  58584. ShaderMaterial.prototype.serialize = function () {
  58585. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58586. serializationObject.customType = "BABYLON.ShaderMaterial";
  58587. serializationObject.options = this._options;
  58588. serializationObject.shaderPath = this._shaderPath;
  58589. var name;
  58590. // Texture
  58591. serializationObject.textures = {};
  58592. for (name in this._textures) {
  58593. serializationObject.textures[name] = this._textures[name].serialize();
  58594. }
  58595. // Texture arrays
  58596. serializationObject.textureArrays = {};
  58597. for (name in this._textureArrays) {
  58598. serializationObject.textureArrays[name] = [];
  58599. var array = this._textureArrays[name];
  58600. for (var index = 0; index < array.length; index++) {
  58601. serializationObject.textureArrays[name].push(array[index].serialize());
  58602. }
  58603. }
  58604. // Float
  58605. serializationObject.floats = {};
  58606. for (name in this._floats) {
  58607. serializationObject.floats[name] = this._floats[name];
  58608. }
  58609. // Float s
  58610. serializationObject.FloatArrays = {};
  58611. for (name in this._floatsArrays) {
  58612. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58613. }
  58614. // Color3
  58615. serializationObject.colors3 = {};
  58616. for (name in this._colors3) {
  58617. serializationObject.colors3[name] = this._colors3[name].asArray();
  58618. }
  58619. // Color3 array
  58620. serializationObject.colors3Arrays = {};
  58621. for (name in this._colors3Arrays) {
  58622. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58623. }
  58624. // Color4
  58625. serializationObject.colors4 = {};
  58626. for (name in this._colors4) {
  58627. serializationObject.colors4[name] = this._colors4[name].asArray();
  58628. }
  58629. // Vector2
  58630. serializationObject.vectors2 = {};
  58631. for (name in this._vectors2) {
  58632. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58633. }
  58634. // Vector3
  58635. serializationObject.vectors3 = {};
  58636. for (name in this._vectors3) {
  58637. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58638. }
  58639. // Vector4
  58640. serializationObject.vectors4 = {};
  58641. for (name in this._vectors4) {
  58642. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58643. }
  58644. // Matrix
  58645. serializationObject.matrices = {};
  58646. for (name in this._matrices) {
  58647. serializationObject.matrices[name] = this._matrices[name].asArray();
  58648. }
  58649. // Matrix 3x3
  58650. serializationObject.matrices3x3 = {};
  58651. for (name in this._matrices3x3) {
  58652. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58653. }
  58654. // Matrix 2x2
  58655. serializationObject.matrices2x2 = {};
  58656. for (name in this._matrices2x2) {
  58657. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58658. }
  58659. // Vector2Array
  58660. serializationObject.vectors2Arrays = {};
  58661. for (name in this._vectors2Arrays) {
  58662. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58663. }
  58664. // Vector3Array
  58665. serializationObject.vectors3Arrays = {};
  58666. for (name in this._vectors3Arrays) {
  58667. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58668. }
  58669. return serializationObject;
  58670. };
  58671. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58672. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58673. var name;
  58674. // Texture
  58675. for (name in source.textures) {
  58676. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58677. }
  58678. // Texture arrays
  58679. for (name in source.textureArrays) {
  58680. var array = source.textureArrays[name];
  58681. var textureArray = new Array();
  58682. for (var index = 0; index < array.length; index++) {
  58683. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58684. }
  58685. material.setTextureArray(name, textureArray);
  58686. }
  58687. // Float
  58688. for (name in source.floats) {
  58689. material.setFloat(name, source.floats[name]);
  58690. }
  58691. // Float s
  58692. for (name in source.floatsArrays) {
  58693. material.setFloats(name, source.floatsArrays[name]);
  58694. }
  58695. // Color3
  58696. for (name in source.colors3) {
  58697. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58698. }
  58699. // Color3 arrays
  58700. for (name in source.colors3Arrays) {
  58701. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58702. if (i % 3 === 0) {
  58703. arr.push([num]);
  58704. }
  58705. else {
  58706. arr[arr.length - 1].push(num);
  58707. }
  58708. return arr;
  58709. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58710. material.setColor3Array(name, colors);
  58711. }
  58712. // Color4
  58713. for (name in source.colors4) {
  58714. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58715. }
  58716. // Vector2
  58717. for (name in source.vectors2) {
  58718. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58719. }
  58720. // Vector3
  58721. for (name in source.vectors3) {
  58722. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58723. }
  58724. // Vector4
  58725. for (name in source.vectors4) {
  58726. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58727. }
  58728. // Matrix
  58729. for (name in source.matrices) {
  58730. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58731. }
  58732. // Matrix 3x3
  58733. for (name in source.matrices3x3) {
  58734. material.setMatrix3x3(name, source.matrices3x3[name]);
  58735. }
  58736. // Matrix 2x2
  58737. for (name in source.matrices2x2) {
  58738. material.setMatrix2x2(name, source.matrices2x2[name]);
  58739. }
  58740. // Vector2Array
  58741. for (name in source.vectors2Arrays) {
  58742. material.setArray2(name, source.vectors2Arrays[name]);
  58743. }
  58744. // Vector3Array
  58745. for (name in source.vectors3Arrays) {
  58746. material.setArray3(name, source.vectors3Arrays[name]);
  58747. }
  58748. return material;
  58749. };
  58750. return ShaderMaterial;
  58751. }(BABYLON.Material));
  58752. BABYLON.ShaderMaterial = ShaderMaterial;
  58753. })(BABYLON || (BABYLON = {}));
  58754. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58755. var BABYLON;
  58756. (function (BABYLON) {
  58757. var GroundMesh = /** @class */ (function (_super) {
  58758. __extends(GroundMesh, _super);
  58759. function GroundMesh(name, scene) {
  58760. var _this = _super.call(this, name, scene) || this;
  58761. _this.generateOctree = false;
  58762. return _this;
  58763. }
  58764. GroundMesh.prototype.getClassName = function () {
  58765. return "GroundMesh";
  58766. };
  58767. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58768. get: function () {
  58769. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58770. },
  58771. enumerable: true,
  58772. configurable: true
  58773. });
  58774. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58775. get: function () {
  58776. return this._subdivisionsX;
  58777. },
  58778. enumerable: true,
  58779. configurable: true
  58780. });
  58781. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58782. get: function () {
  58783. return this._subdivisionsY;
  58784. },
  58785. enumerable: true,
  58786. configurable: true
  58787. });
  58788. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58789. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58790. this._subdivisionsX = chunksCount;
  58791. this._subdivisionsY = chunksCount;
  58792. this.subdivide(chunksCount);
  58793. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58794. };
  58795. /**
  58796. * Returns a height (y) value in the Worl system :
  58797. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58798. * Returns the ground y position if (x, z) are outside the ground surface.
  58799. */
  58800. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58801. var world = this.getWorldMatrix();
  58802. var invMat = BABYLON.Tmp.Matrix[5];
  58803. world.invertToRef(invMat);
  58804. var tmpVect = BABYLON.Tmp.Vector3[8];
  58805. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58806. x = tmpVect.x;
  58807. z = tmpVect.z;
  58808. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58809. return this.position.y;
  58810. }
  58811. if (!this._heightQuads || this._heightQuads.length == 0) {
  58812. this._initHeightQuads();
  58813. this._computeHeightQuads();
  58814. }
  58815. var facet = this._getFacetAt(x, z);
  58816. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58817. // return y in the World system
  58818. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58819. return tmpVect.y;
  58820. };
  58821. /**
  58822. * Returns a normalized vector (Vector3) orthogonal to the ground
  58823. * at the ground coordinates (x, z) expressed in the World system.
  58824. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58825. */
  58826. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58827. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58828. this.getNormalAtCoordinatesToRef(x, z, normal);
  58829. return normal;
  58830. };
  58831. /**
  58832. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58833. * at the ground coordinates (x, z) expressed in the World system.
  58834. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58835. * Returns the GroundMesh.
  58836. */
  58837. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58838. var world = this.getWorldMatrix();
  58839. var tmpMat = BABYLON.Tmp.Matrix[5];
  58840. world.invertToRef(tmpMat);
  58841. var tmpVect = BABYLON.Tmp.Vector3[8];
  58842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58843. x = tmpVect.x;
  58844. z = tmpVect.z;
  58845. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58846. return this;
  58847. }
  58848. if (!this._heightQuads || this._heightQuads.length == 0) {
  58849. this._initHeightQuads();
  58850. this._computeHeightQuads();
  58851. }
  58852. var facet = this._getFacetAt(x, z);
  58853. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58854. return this;
  58855. };
  58856. /**
  58857. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58858. * if the ground has been updated.
  58859. * This can be used in the render loop.
  58860. * Returns the GroundMesh.
  58861. */
  58862. GroundMesh.prototype.updateCoordinateHeights = function () {
  58863. if (!this._heightQuads || this._heightQuads.length == 0) {
  58864. this._initHeightQuads();
  58865. }
  58866. this._computeHeightQuads();
  58867. return this;
  58868. };
  58869. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58870. GroundMesh.prototype._getFacetAt = function (x, z) {
  58871. // retrieve col and row from x, z coordinates in the ground local system
  58872. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58873. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58874. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58875. var facet;
  58876. if (z < quad.slope.x * x + quad.slope.y) {
  58877. facet = quad.facet1;
  58878. }
  58879. else {
  58880. facet = quad.facet2;
  58881. }
  58882. return facet;
  58883. };
  58884. // Creates and populates the heightMap array with "facet" elements :
  58885. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58886. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58887. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58888. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58889. // Returns the GroundMesh.
  58890. GroundMesh.prototype._initHeightQuads = function () {
  58891. var subdivisionsX = this._subdivisionsX;
  58892. var subdivisionsY = this._subdivisionsY;
  58893. this._heightQuads = new Array();
  58894. for (var row = 0; row < subdivisionsY; row++) {
  58895. for (var col = 0; col < subdivisionsX; col++) {
  58896. 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) };
  58897. this._heightQuads[row * subdivisionsX + col] = quad;
  58898. }
  58899. }
  58900. return this;
  58901. };
  58902. // Compute each quad element values and update the the heightMap array :
  58903. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58904. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58905. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58906. // Returns the GroundMesh.
  58907. GroundMesh.prototype._computeHeightQuads = function () {
  58908. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58909. if (!positions) {
  58910. return this;
  58911. }
  58912. var v1 = BABYLON.Tmp.Vector3[3];
  58913. var v2 = BABYLON.Tmp.Vector3[2];
  58914. var v3 = BABYLON.Tmp.Vector3[1];
  58915. var v4 = BABYLON.Tmp.Vector3[0];
  58916. var v1v2 = BABYLON.Tmp.Vector3[4];
  58917. var v1v3 = BABYLON.Tmp.Vector3[5];
  58918. var v1v4 = BABYLON.Tmp.Vector3[6];
  58919. var norm1 = BABYLON.Tmp.Vector3[7];
  58920. var norm2 = BABYLON.Tmp.Vector3[8];
  58921. var i = 0;
  58922. var j = 0;
  58923. var k = 0;
  58924. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58925. var h = 0;
  58926. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58927. var d2 = 0;
  58928. var subdivisionsX = this._subdivisionsX;
  58929. var subdivisionsY = this._subdivisionsY;
  58930. for (var row = 0; row < subdivisionsY; row++) {
  58931. for (var col = 0; col < subdivisionsX; col++) {
  58932. i = col * 3;
  58933. j = row * (subdivisionsX + 1) * 3;
  58934. k = (row + 1) * (subdivisionsX + 1) * 3;
  58935. v1.x = positions[j + i];
  58936. v1.y = positions[j + i + 1];
  58937. v1.z = positions[j + i + 2];
  58938. v2.x = positions[j + i + 3];
  58939. v2.y = positions[j + i + 4];
  58940. v2.z = positions[j + i + 5];
  58941. v3.x = positions[k + i];
  58942. v3.y = positions[k + i + 1];
  58943. v3.z = positions[k + i + 2];
  58944. v4.x = positions[k + i + 3];
  58945. v4.y = positions[k + i + 4];
  58946. v4.z = positions[k + i + 5];
  58947. // 2D slope V1V4
  58948. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58949. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58950. // facet equations :
  58951. // we compute each facet normal vector
  58952. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58953. // we compute the value d by applying the equation to v1 which belongs to the plane
  58954. // then we store the facet equation in a Vector4
  58955. v2.subtractToRef(v1, v1v2);
  58956. v3.subtractToRef(v1, v1v3);
  58957. v4.subtractToRef(v1, v1v4);
  58958. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58959. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58960. norm1.normalize();
  58961. norm2.normalize();
  58962. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58963. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58964. var quad = this._heightQuads[row * subdivisionsX + col];
  58965. quad.slope.copyFromFloats(cd, h);
  58966. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58967. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58968. }
  58969. }
  58970. return this;
  58971. };
  58972. GroundMesh.prototype.serialize = function (serializationObject) {
  58973. _super.prototype.serialize.call(this, serializationObject);
  58974. serializationObject.subdivisionsX = this._subdivisionsX;
  58975. serializationObject.subdivisionsY = this._subdivisionsY;
  58976. serializationObject.minX = this._minX;
  58977. serializationObject.maxX = this._maxX;
  58978. serializationObject.minZ = this._minZ;
  58979. serializationObject.maxZ = this._maxZ;
  58980. serializationObject.width = this._width;
  58981. serializationObject.height = this._height;
  58982. };
  58983. GroundMesh.Parse = function (parsedMesh, scene) {
  58984. var result = new GroundMesh(parsedMesh.name, scene);
  58985. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58986. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58987. result._minX = parsedMesh.minX;
  58988. result._maxX = parsedMesh.maxX;
  58989. result._minZ = parsedMesh.minZ;
  58990. result._maxZ = parsedMesh.maxZ;
  58991. result._width = parsedMesh.width;
  58992. result._height = parsedMesh.height;
  58993. return result;
  58994. };
  58995. return GroundMesh;
  58996. }(BABYLON.Mesh));
  58997. BABYLON.GroundMesh = GroundMesh;
  58998. })(BABYLON || (BABYLON = {}));
  58999. //# sourceMappingURL=babylon.groundMesh.js.map
  59000. var BABYLON;
  59001. (function (BABYLON) {
  59002. /**
  59003. * Creates an instance based on a source mesh.
  59004. */
  59005. var InstancedMesh = /** @class */ (function (_super) {
  59006. __extends(InstancedMesh, _super);
  59007. function InstancedMesh(name, source) {
  59008. var _this = _super.call(this, name, source.getScene()) || this;
  59009. source.instances.push(_this);
  59010. _this._sourceMesh = source;
  59011. _this.position.copyFrom(source.position);
  59012. _this.rotation.copyFrom(source.rotation);
  59013. _this.scaling.copyFrom(source.scaling);
  59014. if (source.rotationQuaternion) {
  59015. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59016. }
  59017. _this.infiniteDistance = source.infiniteDistance;
  59018. _this.setPivotMatrix(source.getPivotMatrix());
  59019. _this.refreshBoundingInfo();
  59020. _this._syncSubMeshes();
  59021. return _this;
  59022. }
  59023. /**
  59024. * Returns the string "InstancedMesh".
  59025. */
  59026. InstancedMesh.prototype.getClassName = function () {
  59027. return "InstancedMesh";
  59028. };
  59029. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59030. // Methods
  59031. get: function () {
  59032. return this._sourceMesh.receiveShadows;
  59033. },
  59034. enumerable: true,
  59035. configurable: true
  59036. });
  59037. Object.defineProperty(InstancedMesh.prototype, "material", {
  59038. get: function () {
  59039. return this._sourceMesh.material;
  59040. },
  59041. enumerable: true,
  59042. configurable: true
  59043. });
  59044. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59045. get: function () {
  59046. return this._sourceMesh.visibility;
  59047. },
  59048. enumerable: true,
  59049. configurable: true
  59050. });
  59051. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59052. get: function () {
  59053. return this._sourceMesh.skeleton;
  59054. },
  59055. enumerable: true,
  59056. configurable: true
  59057. });
  59058. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59059. get: function () {
  59060. return this._sourceMesh.renderingGroupId;
  59061. },
  59062. set: function (value) {
  59063. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59064. return;
  59065. }
  59066. //no-op with warning
  59067. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59068. },
  59069. enumerable: true,
  59070. configurable: true
  59071. });
  59072. /**
  59073. * Returns the total number of vertices (integer).
  59074. */
  59075. InstancedMesh.prototype.getTotalVertices = function () {
  59076. return this._sourceMesh.getTotalVertices();
  59077. };
  59078. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59079. get: function () {
  59080. return this._sourceMesh;
  59081. },
  59082. enumerable: true,
  59083. configurable: true
  59084. });
  59085. /**
  59086. * Is this node ready to be used/rendered
  59087. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59088. * @return {boolean} is it ready
  59089. */
  59090. InstancedMesh.prototype.isReady = function (completeCheck) {
  59091. if (completeCheck === void 0) { completeCheck = false; }
  59092. return this._sourceMesh.isReady(completeCheck, true);
  59093. };
  59094. /**
  59095. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59096. */
  59097. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59098. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59099. };
  59100. /**
  59101. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59102. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59103. * The `data` are either a numeric array either a Float32Array.
  59104. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59105. * 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).
  59106. * Note that a new underlying VertexBuffer object is created each call.
  59107. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59108. *
  59109. * Possible `kind` values :
  59110. * - BABYLON.VertexBuffer.PositionKind
  59111. * - BABYLON.VertexBuffer.UVKind
  59112. * - BABYLON.VertexBuffer.UV2Kind
  59113. * - BABYLON.VertexBuffer.UV3Kind
  59114. * - BABYLON.VertexBuffer.UV4Kind
  59115. * - BABYLON.VertexBuffer.UV5Kind
  59116. * - BABYLON.VertexBuffer.UV6Kind
  59117. * - BABYLON.VertexBuffer.ColorKind
  59118. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59119. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59120. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59121. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59122. *
  59123. * Returns the Mesh.
  59124. */
  59125. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59126. if (this.sourceMesh) {
  59127. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59128. }
  59129. return this.sourceMesh;
  59130. };
  59131. /**
  59132. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59133. * If the mesh has no geometry, it is simply returned as it is.
  59134. * The `data` are either a numeric array either a Float32Array.
  59135. * No new underlying VertexBuffer object is created.
  59136. * 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.
  59137. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59138. *
  59139. * Possible `kind` values :
  59140. * - BABYLON.VertexBuffer.PositionKind
  59141. * - BABYLON.VertexBuffer.UVKind
  59142. * - BABYLON.VertexBuffer.UV2Kind
  59143. * - BABYLON.VertexBuffer.UV3Kind
  59144. * - BABYLON.VertexBuffer.UV4Kind
  59145. * - BABYLON.VertexBuffer.UV5Kind
  59146. * - BABYLON.VertexBuffer.UV6Kind
  59147. * - BABYLON.VertexBuffer.ColorKind
  59148. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59149. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59150. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59151. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59152. *
  59153. * Returns the Mesh.
  59154. */
  59155. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59156. if (this.sourceMesh) {
  59157. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59158. }
  59159. return this.sourceMesh;
  59160. };
  59161. /**
  59162. * Sets the mesh indices.
  59163. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59164. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59165. * This method creates a new index buffer each call.
  59166. * Returns the Mesh.
  59167. */
  59168. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59169. if (totalVertices === void 0) { totalVertices = null; }
  59170. if (this.sourceMesh) {
  59171. this.sourceMesh.setIndices(indices, totalVertices);
  59172. }
  59173. return this.sourceMesh;
  59174. };
  59175. /**
  59176. * Boolean : True if the mesh owns the requested kind of data.
  59177. */
  59178. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59179. return this._sourceMesh.isVerticesDataPresent(kind);
  59180. };
  59181. /**
  59182. * Returns an array of indices (IndicesArray).
  59183. */
  59184. InstancedMesh.prototype.getIndices = function () {
  59185. return this._sourceMesh.getIndices();
  59186. };
  59187. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59188. get: function () {
  59189. return this._sourceMesh._positions;
  59190. },
  59191. enumerable: true,
  59192. configurable: true
  59193. });
  59194. /**
  59195. * Sets a new updated BoundingInfo to the mesh.
  59196. * Returns the mesh.
  59197. */
  59198. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59199. var meshBB = this._sourceMesh.getBoundingInfo();
  59200. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59201. this._updateBoundingInfo();
  59202. return this;
  59203. };
  59204. /** @hidden */
  59205. InstancedMesh.prototype._preActivate = function () {
  59206. if (this._currentLOD) {
  59207. this._currentLOD._preActivate();
  59208. }
  59209. return this;
  59210. };
  59211. /** @hidden */
  59212. InstancedMesh.prototype._activate = function (renderId) {
  59213. if (this._currentLOD) {
  59214. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59215. }
  59216. return this;
  59217. };
  59218. /**
  59219. * Returns the current associated LOD AbstractMesh.
  59220. */
  59221. InstancedMesh.prototype.getLOD = function (camera) {
  59222. if (!camera) {
  59223. return this;
  59224. }
  59225. var boundingInfo = this.getBoundingInfo();
  59226. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59227. if (this._currentLOD === this.sourceMesh) {
  59228. return this;
  59229. }
  59230. return this._currentLOD;
  59231. };
  59232. /** @hidden */
  59233. InstancedMesh.prototype._syncSubMeshes = function () {
  59234. this.releaseSubMeshes();
  59235. if (this._sourceMesh.subMeshes) {
  59236. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59237. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59238. }
  59239. }
  59240. return this;
  59241. };
  59242. /** @hidden */
  59243. InstancedMesh.prototype._generatePointsArray = function () {
  59244. return this._sourceMesh._generatePointsArray();
  59245. };
  59246. /**
  59247. * Creates a new InstancedMesh from the current mesh.
  59248. * - name (string) : the cloned mesh name
  59249. * - newParent (optional Node) : the optional Node to parent the clone to.
  59250. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59251. *
  59252. * Returns the clone.
  59253. */
  59254. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59255. var result = this._sourceMesh.createInstance(name);
  59256. // Deep copy
  59257. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59258. // Bounding info
  59259. this.refreshBoundingInfo();
  59260. // Parent
  59261. if (newParent) {
  59262. result.parent = newParent;
  59263. }
  59264. if (!doNotCloneChildren) {
  59265. // Children
  59266. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59267. var mesh = this.getScene().meshes[index];
  59268. if (mesh.parent === this) {
  59269. mesh.clone(mesh.name, result);
  59270. }
  59271. }
  59272. }
  59273. result.computeWorldMatrix(true);
  59274. return result;
  59275. };
  59276. /**
  59277. * Disposes the InstancedMesh.
  59278. * Returns nothing.
  59279. */
  59280. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59281. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59282. // Remove from mesh
  59283. var index = this._sourceMesh.instances.indexOf(this);
  59284. this._sourceMesh.instances.splice(index, 1);
  59285. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59286. };
  59287. return InstancedMesh;
  59288. }(BABYLON.AbstractMesh));
  59289. BABYLON.InstancedMesh = InstancedMesh;
  59290. })(BABYLON || (BABYLON = {}));
  59291. //# sourceMappingURL=babylon.instancedMesh.js.map
  59292. var BABYLON;
  59293. (function (BABYLON) {
  59294. var LinesMesh = /** @class */ (function (_super) {
  59295. __extends(LinesMesh, _super);
  59296. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59297. if (scene === void 0) { scene = null; }
  59298. if (parent === void 0) { parent = null; }
  59299. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59300. _this.useVertexColor = useVertexColor;
  59301. _this.useVertexAlpha = useVertexAlpha;
  59302. _this.color = new BABYLON.Color3(1, 1, 1);
  59303. _this.alpha = 1;
  59304. if (source) {
  59305. _this.color = source.color.clone();
  59306. _this.alpha = source.alpha;
  59307. _this.useVertexColor = source.useVertexColor;
  59308. _this.useVertexAlpha = source.useVertexAlpha;
  59309. }
  59310. _this._intersectionThreshold = 0.1;
  59311. var defines = [];
  59312. var options = {
  59313. attributes: [BABYLON.VertexBuffer.PositionKind],
  59314. uniforms: ["world", "viewProjection"],
  59315. needAlphaBlending: true,
  59316. defines: defines
  59317. };
  59318. if (useVertexAlpha === false) {
  59319. options.needAlphaBlending = false;
  59320. }
  59321. if (!useVertexColor) {
  59322. options.uniforms.push("color");
  59323. }
  59324. else {
  59325. options.defines.push("#define VERTEXCOLOR");
  59326. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59327. }
  59328. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59329. return _this;
  59330. }
  59331. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59332. /**
  59333. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59334. * This margin is expressed in world space coordinates, so its value may vary.
  59335. * Default value is 0.1
  59336. * @returns the intersection Threshold value.
  59337. */
  59338. get: function () {
  59339. return this._intersectionThreshold;
  59340. },
  59341. /**
  59342. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59343. * This margin is expressed in world space coordinates, so its value may vary.
  59344. * @param value the new threshold to apply
  59345. */
  59346. set: function (value) {
  59347. if (this._intersectionThreshold === value) {
  59348. return;
  59349. }
  59350. this._intersectionThreshold = value;
  59351. if (this.geometry) {
  59352. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59353. }
  59354. },
  59355. enumerable: true,
  59356. configurable: true
  59357. });
  59358. /**
  59359. * Returns the string "LineMesh"
  59360. */
  59361. LinesMesh.prototype.getClassName = function () {
  59362. return "LinesMesh";
  59363. };
  59364. Object.defineProperty(LinesMesh.prototype, "material", {
  59365. /**
  59366. * @hidden
  59367. */
  59368. get: function () {
  59369. return this._colorShader;
  59370. },
  59371. /**
  59372. * @hidden
  59373. */
  59374. set: function (value) {
  59375. // Do nothing
  59376. },
  59377. enumerable: true,
  59378. configurable: true
  59379. });
  59380. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59381. /**
  59382. * @hidden
  59383. */
  59384. get: function () {
  59385. return false;
  59386. },
  59387. enumerable: true,
  59388. configurable: true
  59389. });
  59390. LinesMesh.prototype.createInstance = function (name) {
  59391. throw new Error("LinesMeshes do not support createInstance.");
  59392. };
  59393. /** @hidden */
  59394. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59395. if (!this._geometry) {
  59396. return this;
  59397. }
  59398. // VBOs
  59399. this._geometry._bind(this._colorShader.getEffect());
  59400. // Color
  59401. if (!this.useVertexColor) {
  59402. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59403. }
  59404. return this;
  59405. };
  59406. /** @hidden */
  59407. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59408. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59409. return this;
  59410. }
  59411. var engine = this.getScene().getEngine();
  59412. // Draw order
  59413. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59414. return this;
  59415. };
  59416. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59417. this._colorShader.dispose();
  59418. _super.prototype.dispose.call(this, doNotRecurse);
  59419. };
  59420. /**
  59421. * Returns a new LineMesh object cloned from the current one.
  59422. */
  59423. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59424. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59425. };
  59426. /**
  59427. * Enables the edge rendering mode on the mesh.
  59428. * This mode makes the mesh edges visible
  59429. * @param epsilon defines the maximal distance between two angles to detect a face
  59430. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  59431. * @returns the currentAbstractMesh
  59432. * @see https://www.babylonjs-playground.com/#19O9TU#0
  59433. */
  59434. LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  59435. if (epsilon === void 0) { epsilon = 0.95; }
  59436. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59437. this.disableEdgesRendering();
  59438. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  59439. return this;
  59440. };
  59441. return LinesMesh;
  59442. }(BABYLON.Mesh));
  59443. BABYLON.LinesMesh = LinesMesh;
  59444. })(BABYLON || (BABYLON = {}));
  59445. //# sourceMappingURL=babylon.linesMesh.js.map
  59446. var BABYLON;
  59447. (function (BABYLON) {
  59448. /**
  59449. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59450. * The underlying implementation relies on an associative array to ensure the best performances.
  59451. * The value can be anything including 'null' but except 'undefined'
  59452. */
  59453. var StringDictionary = /** @class */ (function () {
  59454. function StringDictionary() {
  59455. this._count = 0;
  59456. this._data = {};
  59457. }
  59458. /**
  59459. * This will clear this dictionary and copy the content from the 'source' one.
  59460. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59461. * @param source the dictionary to take the content from and copy to this dictionary
  59462. */
  59463. StringDictionary.prototype.copyFrom = function (source) {
  59464. var _this = this;
  59465. this.clear();
  59466. source.forEach(function (t, v) { return _this.add(t, v); });
  59467. };
  59468. /**
  59469. * Get a value based from its key
  59470. * @param key the given key to get the matching value from
  59471. * @return the value if found, otherwise undefined is returned
  59472. */
  59473. StringDictionary.prototype.get = function (key) {
  59474. var val = this._data[key];
  59475. if (val !== undefined) {
  59476. return val;
  59477. }
  59478. return undefined;
  59479. };
  59480. /**
  59481. * Get a value from its key or add it if it doesn't exist.
  59482. * This method will ensure you that a given key/data will be present in the dictionary.
  59483. * @param key the given key to get the matching value from
  59484. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59485. * The factory will only be invoked if there's no data for the given key.
  59486. * @return the value corresponding to the key.
  59487. */
  59488. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59489. var val = this.get(key);
  59490. if (val !== undefined) {
  59491. return val;
  59492. }
  59493. val = factory(key);
  59494. if (val) {
  59495. this.add(key, val);
  59496. }
  59497. return val;
  59498. };
  59499. /**
  59500. * Get a value from its key if present in the dictionary otherwise add it
  59501. * @param key the key to get the value from
  59502. * @param val if there's no such key/value pair in the dictionary add it with this value
  59503. * @return the value corresponding to the key
  59504. */
  59505. StringDictionary.prototype.getOrAdd = function (key, val) {
  59506. var curVal = this.get(key);
  59507. if (curVal !== undefined) {
  59508. return curVal;
  59509. }
  59510. this.add(key, val);
  59511. return val;
  59512. };
  59513. /**
  59514. * Check if there's a given key in the dictionary
  59515. * @param key the key to check for
  59516. * @return true if the key is present, false otherwise
  59517. */
  59518. StringDictionary.prototype.contains = function (key) {
  59519. return this._data[key] !== undefined;
  59520. };
  59521. /**
  59522. * Add a new key and its corresponding value
  59523. * @param key the key to add
  59524. * @param value the value corresponding to the key
  59525. * @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
  59526. */
  59527. StringDictionary.prototype.add = function (key, value) {
  59528. if (this._data[key] !== undefined) {
  59529. return false;
  59530. }
  59531. this._data[key] = value;
  59532. ++this._count;
  59533. return true;
  59534. };
  59535. StringDictionary.prototype.set = function (key, value) {
  59536. if (this._data[key] === undefined) {
  59537. return false;
  59538. }
  59539. this._data[key] = value;
  59540. return true;
  59541. };
  59542. /**
  59543. * Get the element of the given key and remove it from the dictionary
  59544. * @param key
  59545. */
  59546. StringDictionary.prototype.getAndRemove = function (key) {
  59547. var val = this.get(key);
  59548. if (val !== undefined) {
  59549. delete this._data[key];
  59550. --this._count;
  59551. return val;
  59552. }
  59553. return null;
  59554. };
  59555. /**
  59556. * Remove a key/value from the dictionary.
  59557. * @param key the key to remove
  59558. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59559. */
  59560. StringDictionary.prototype.remove = function (key) {
  59561. if (this.contains(key)) {
  59562. delete this._data[key];
  59563. --this._count;
  59564. return true;
  59565. }
  59566. return false;
  59567. };
  59568. /**
  59569. * Clear the whole content of the dictionary
  59570. */
  59571. StringDictionary.prototype.clear = function () {
  59572. this._data = {};
  59573. this._count = 0;
  59574. };
  59575. Object.defineProperty(StringDictionary.prototype, "count", {
  59576. get: function () {
  59577. return this._count;
  59578. },
  59579. enumerable: true,
  59580. configurable: true
  59581. });
  59582. /**
  59583. * Execute a callback on each key/val of the dictionary.
  59584. * Note that you can remove any element in this dictionary in the callback implementation
  59585. * @param callback the callback to execute on a given key/value pair
  59586. */
  59587. StringDictionary.prototype.forEach = function (callback) {
  59588. for (var cur in this._data) {
  59589. var val = this._data[cur];
  59590. callback(cur, val);
  59591. }
  59592. };
  59593. /**
  59594. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59595. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59596. * Note that you can remove any element in this dictionary in the callback implementation
  59597. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59598. */
  59599. StringDictionary.prototype.first = function (callback) {
  59600. for (var cur in this._data) {
  59601. var val = this._data[cur];
  59602. var res = callback(cur, val);
  59603. if (res) {
  59604. return res;
  59605. }
  59606. }
  59607. return null;
  59608. };
  59609. return StringDictionary;
  59610. }());
  59611. BABYLON.StringDictionary = StringDictionary;
  59612. })(BABYLON || (BABYLON = {}));
  59613. //# sourceMappingURL=babylon.stringDictionary.js.map
  59614. var BABYLON;
  59615. (function (BABYLON) {
  59616. var Debug;
  59617. (function (Debug) {
  59618. /**
  59619. * Class used to render a debug view of a given skeleton
  59620. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59621. */
  59622. var SkeletonViewer = /** @class */ (function () {
  59623. /**
  59624. * Creates a new SkeletonViewer
  59625. * @param skeleton defines the skeleton to render
  59626. * @param mesh defines the mesh attached to the skeleton
  59627. * @param scene defines the hosting scene
  59628. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59629. * @param renderingGroupId defines the rendering group id to use with the viewer
  59630. */
  59631. function SkeletonViewer(
  59632. /** defines the skeleton to render */
  59633. skeleton,
  59634. /** defines the mesh attached to the skeleton */
  59635. mesh, scene,
  59636. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59637. autoUpdateBonesMatrices,
  59638. /** defines the rendering group id to use with the viewer */
  59639. renderingGroupId) {
  59640. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59641. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59642. this.skeleton = skeleton;
  59643. this.mesh = mesh;
  59644. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59645. this.renderingGroupId = renderingGroupId;
  59646. /** Gets or sets the color used to render the skeleton */
  59647. this.color = BABYLON.Color3.White();
  59648. this._debugLines = new Array();
  59649. this._isEnabled = false;
  59650. this._scene = scene;
  59651. this.update();
  59652. this._renderFunction = this.update.bind(this);
  59653. }
  59654. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59655. get: function () {
  59656. return this._isEnabled;
  59657. },
  59658. /** Gets or sets a boolean indicating if the viewer is enabled */
  59659. set: function (value) {
  59660. if (this._isEnabled === value) {
  59661. return;
  59662. }
  59663. this._isEnabled = value;
  59664. if (value) {
  59665. this._scene.registerBeforeRender(this._renderFunction);
  59666. }
  59667. else {
  59668. this._scene.unregisterBeforeRender(this._renderFunction);
  59669. }
  59670. },
  59671. enumerable: true,
  59672. configurable: true
  59673. });
  59674. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59675. if (x === void 0) { x = 0; }
  59676. if (y === void 0) { y = 0; }
  59677. if (z === void 0) { z = 0; }
  59678. var tmat = BABYLON.Tmp.Matrix[0];
  59679. var parentBone = bone.getParent();
  59680. tmat.copyFrom(bone.getLocalMatrix());
  59681. if (x !== 0 || y !== 0 || z !== 0) {
  59682. var tmat2 = BABYLON.Tmp.Matrix[1];
  59683. BABYLON.Matrix.IdentityToRef(tmat2);
  59684. tmat2.m[12] = x;
  59685. tmat2.m[13] = y;
  59686. tmat2.m[14] = z;
  59687. tmat2.multiplyToRef(tmat, tmat);
  59688. }
  59689. if (parentBone) {
  59690. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59691. }
  59692. tmat.multiplyToRef(meshMat, tmat);
  59693. position.x = tmat.m[12];
  59694. position.y = tmat.m[13];
  59695. position.z = tmat.m[14];
  59696. };
  59697. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59698. var len = bones.length;
  59699. var meshPos = this.mesh.position;
  59700. for (var i = 0; i < len; i++) {
  59701. var bone = bones[i];
  59702. var points = this._debugLines[i];
  59703. if (!points) {
  59704. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59705. this._debugLines[i] = points;
  59706. }
  59707. this._getBonePosition(points[0], bone, meshMat);
  59708. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59709. points[0].subtractInPlace(meshPos);
  59710. points[1].subtractInPlace(meshPos);
  59711. }
  59712. };
  59713. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59714. var len = bones.length;
  59715. var boneNum = 0;
  59716. var meshPos = this.mesh.position;
  59717. for (var i = len - 1; i >= 0; i--) {
  59718. var childBone = bones[i];
  59719. var parentBone = childBone.getParent();
  59720. if (!parentBone) {
  59721. continue;
  59722. }
  59723. var points = this._debugLines[boneNum];
  59724. if (!points) {
  59725. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59726. this._debugLines[boneNum] = points;
  59727. }
  59728. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59729. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59730. points[0].subtractInPlace(meshPos);
  59731. points[1].subtractInPlace(meshPos);
  59732. boneNum++;
  59733. }
  59734. };
  59735. /** Update the viewer to sync with current skeleton state */
  59736. SkeletonViewer.prototype.update = function () {
  59737. if (this.autoUpdateBonesMatrices) {
  59738. this.skeleton.computeAbsoluteTransforms();
  59739. }
  59740. if (this.skeleton.bones[0].length === undefined) {
  59741. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59742. }
  59743. else {
  59744. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59745. }
  59746. if (!this._debugMesh) {
  59747. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59748. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59749. }
  59750. else {
  59751. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59752. }
  59753. this._debugMesh.position.copyFrom(this.mesh.position);
  59754. this._debugMesh.color = this.color;
  59755. };
  59756. /** Release associated resources */
  59757. SkeletonViewer.prototype.dispose = function () {
  59758. if (this._debugMesh) {
  59759. this.isEnabled = false;
  59760. this._debugMesh.dispose();
  59761. this._debugMesh = null;
  59762. }
  59763. };
  59764. return SkeletonViewer;
  59765. }());
  59766. Debug.SkeletonViewer = SkeletonViewer;
  59767. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59768. })(BABYLON || (BABYLON = {}));
  59769. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59770. /**
  59771. * Module Debug contains the (visual) components to debug a scene correctly
  59772. */
  59773. var BABYLON;
  59774. (function (BABYLON) {
  59775. var Debug;
  59776. (function (Debug) {
  59777. /**
  59778. * The Axes viewer will show 3 axes in a specific point in space
  59779. */
  59780. var AxesViewer = /** @class */ (function () {
  59781. /**
  59782. * Creates a new AxesViewer
  59783. * @param scene defines the hosting scene
  59784. * @param scaleLines defines a number used to scale line length (1 by default)
  59785. */
  59786. function AxesViewer(scene, scaleLines) {
  59787. if (scaleLines === void 0) { scaleLines = 1; }
  59788. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59789. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59790. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59791. /**
  59792. * Gets or sets a number used to scale line length
  59793. */
  59794. this.scaleLines = 1;
  59795. this.scaleLines = scaleLines;
  59796. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59797. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59798. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59799. this._xmesh.renderingGroupId = 2;
  59800. this._ymesh.renderingGroupId = 2;
  59801. this._zmesh.renderingGroupId = 2;
  59802. this._xmesh.material.checkReadyOnlyOnce = true;
  59803. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59804. this._ymesh.material.checkReadyOnlyOnce = true;
  59805. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59806. this._zmesh.material.checkReadyOnlyOnce = true;
  59807. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59808. this.scene = scene;
  59809. }
  59810. /**
  59811. * Force the viewer to update
  59812. * @param position defines the position of the viewer
  59813. * @param xaxis defines the x axis of the viewer
  59814. * @param yaxis defines the y axis of the viewer
  59815. * @param zaxis defines the z axis of the viewer
  59816. */
  59817. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59818. var scaleLines = this.scaleLines;
  59819. if (this._xmesh) {
  59820. this._xmesh.position.copyFrom(position);
  59821. }
  59822. if (this._ymesh) {
  59823. this._ymesh.position.copyFrom(position);
  59824. }
  59825. if (this._zmesh) {
  59826. this._zmesh.position.copyFrom(position);
  59827. }
  59828. var point2 = this._xline[1];
  59829. point2.x = xaxis.x * scaleLines;
  59830. point2.y = xaxis.y * scaleLines;
  59831. point2.z = xaxis.z * scaleLines;
  59832. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  59833. point2 = this._yline[1];
  59834. point2.x = yaxis.x * scaleLines;
  59835. point2.y = yaxis.y * scaleLines;
  59836. point2.z = yaxis.z * scaleLines;
  59837. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  59838. point2 = this._zline[1];
  59839. point2.x = zaxis.x * scaleLines;
  59840. point2.y = zaxis.y * scaleLines;
  59841. point2.z = zaxis.z * scaleLines;
  59842. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  59843. };
  59844. /** Releases resources */
  59845. AxesViewer.prototype.dispose = function () {
  59846. if (this._xmesh) {
  59847. this._xmesh.dispose();
  59848. }
  59849. if (this._ymesh) {
  59850. this._ymesh.dispose();
  59851. }
  59852. if (this._zmesh) {
  59853. this._zmesh.dispose();
  59854. }
  59855. this._xmesh = null;
  59856. this._ymesh = null;
  59857. this._zmesh = null;
  59858. this.scene = null;
  59859. };
  59860. return AxesViewer;
  59861. }());
  59862. Debug.AxesViewer = AxesViewer;
  59863. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59864. })(BABYLON || (BABYLON = {}));
  59865. //# sourceMappingURL=babylon.axesViewer.js.map
  59866. var BABYLON;
  59867. (function (BABYLON) {
  59868. var Debug;
  59869. (function (Debug) {
  59870. /**
  59871. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  59872. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  59873. */
  59874. var BoneAxesViewer = /** @class */ (function (_super) {
  59875. __extends(BoneAxesViewer, _super);
  59876. /**
  59877. * Creates a new BoneAxesViewer
  59878. * @param scene defines the hosting scene
  59879. * @param bone defines the target bone
  59880. * @param mesh defines the target mesh
  59881. * @param scaleLines defines a scaling factor for line length (1 by default)
  59882. */
  59883. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59884. if (scaleLines === void 0) { scaleLines = 1; }
  59885. var _this = _super.call(this, scene, scaleLines) || this;
  59886. /** Gets current position */
  59887. _this.pos = BABYLON.Vector3.Zero();
  59888. /** Gets direction of X axis */
  59889. _this.xaxis = BABYLON.Vector3.Zero();
  59890. /** Gets direction of Y axis */
  59891. _this.yaxis = BABYLON.Vector3.Zero();
  59892. /** Gets direction of Z axis */
  59893. _this.zaxis = BABYLON.Vector3.Zero();
  59894. _this.mesh = mesh;
  59895. _this.bone = bone;
  59896. return _this;
  59897. }
  59898. /**
  59899. * Force the viewer to update
  59900. */
  59901. BoneAxesViewer.prototype.update = function () {
  59902. if (!this.mesh || !this.bone) {
  59903. return;
  59904. }
  59905. var bone = this.bone;
  59906. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59907. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59908. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59909. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59910. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59911. };
  59912. /** Releases resources */
  59913. BoneAxesViewer.prototype.dispose = function () {
  59914. if (this.mesh) {
  59915. this.mesh = null;
  59916. this.bone = null;
  59917. _super.prototype.dispose.call(this);
  59918. }
  59919. };
  59920. return BoneAxesViewer;
  59921. }(Debug.AxesViewer));
  59922. Debug.BoneAxesViewer = BoneAxesViewer;
  59923. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59924. })(BABYLON || (BABYLON = {}));
  59925. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59926. var BABYLON;
  59927. (function (BABYLON) {
  59928. var RayHelper = /** @class */ (function () {
  59929. function RayHelper(ray) {
  59930. this.ray = ray;
  59931. }
  59932. RayHelper.CreateAndShow = function (ray, scene, color) {
  59933. var helper = new RayHelper(ray);
  59934. helper.show(scene, color);
  59935. return helper;
  59936. };
  59937. RayHelper.prototype.show = function (scene, color) {
  59938. if (!this._renderFunction && this.ray) {
  59939. var ray = this.ray;
  59940. this._renderFunction = this._render.bind(this);
  59941. this._scene = scene;
  59942. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59943. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59944. if (this._renderFunction) {
  59945. this._scene.registerBeforeRender(this._renderFunction);
  59946. }
  59947. }
  59948. if (color && this._renderLine) {
  59949. this._renderLine.color.copyFrom(color);
  59950. }
  59951. };
  59952. RayHelper.prototype.hide = function () {
  59953. if (this._renderFunction && this._scene) {
  59954. this._scene.unregisterBeforeRender(this._renderFunction);
  59955. this._scene = null;
  59956. this._renderFunction = null;
  59957. if (this._renderLine) {
  59958. this._renderLine.dispose();
  59959. this._renderLine = null;
  59960. }
  59961. this._renderPoints = [];
  59962. }
  59963. };
  59964. RayHelper.prototype._render = function () {
  59965. var ray = this.ray;
  59966. if (!ray) {
  59967. return;
  59968. }
  59969. var point = this._renderPoints[1];
  59970. var len = Math.min(ray.length, 1000000);
  59971. point.copyFrom(ray.direction);
  59972. point.scaleInPlace(len);
  59973. point.addInPlace(ray.origin);
  59974. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59975. };
  59976. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59977. this._attachedToMesh = mesh;
  59978. var ray = this.ray;
  59979. if (!ray) {
  59980. return;
  59981. }
  59982. if (!ray.direction) {
  59983. ray.direction = BABYLON.Vector3.Zero();
  59984. }
  59985. if (!ray.origin) {
  59986. ray.origin = BABYLON.Vector3.Zero();
  59987. }
  59988. if (length) {
  59989. ray.length = length;
  59990. }
  59991. if (!meshSpaceOrigin) {
  59992. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59993. }
  59994. if (!meshSpaceDirection) {
  59995. // -1 so that this will work with Mesh.lookAt
  59996. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59997. }
  59998. if (!this._meshSpaceDirection) {
  59999. this._meshSpaceDirection = meshSpaceDirection.clone();
  60000. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60001. }
  60002. else {
  60003. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60004. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60005. }
  60006. if (!this._updateToMeshFunction) {
  60007. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60008. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60009. }
  60010. this._updateToMesh();
  60011. };
  60012. RayHelper.prototype.detachFromMesh = function () {
  60013. if (this._attachedToMesh) {
  60014. if (this._updateToMeshFunction) {
  60015. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60016. }
  60017. this._attachedToMesh = null;
  60018. this._updateToMeshFunction = null;
  60019. }
  60020. };
  60021. RayHelper.prototype._updateToMesh = function () {
  60022. var ray = this.ray;
  60023. if (!this._attachedToMesh || !ray) {
  60024. return;
  60025. }
  60026. if (this._attachedToMesh._isDisposed) {
  60027. this.detachFromMesh();
  60028. return;
  60029. }
  60030. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60031. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60032. };
  60033. RayHelper.prototype.dispose = function () {
  60034. this.hide();
  60035. this.detachFromMesh();
  60036. this.ray = null;
  60037. };
  60038. return RayHelper;
  60039. }());
  60040. BABYLON.RayHelper = RayHelper;
  60041. })(BABYLON || (BABYLON = {}));
  60042. //# sourceMappingURL=babylon.rayHelper.js.map
  60043. var BABYLON;
  60044. (function (BABYLON) {
  60045. // load the inspector using require, if not present in the global namespace.
  60046. var DebugLayer = /** @class */ (function () {
  60047. function DebugLayer(scene) {
  60048. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60049. this.onPropertyChangedObservable = new BABYLON.Observable();
  60050. this._scene = scene;
  60051. }
  60052. /** Creates the inspector window. */
  60053. DebugLayer.prototype._createInspector = function (config) {
  60054. if (config === void 0) { config = {}; }
  60055. var popup = config.popup || false;
  60056. var initialTab = config.initialTab || 0;
  60057. var parentElement = config.parentElement || null;
  60058. if (!this._inspector) {
  60059. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60060. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60061. } // else nothing to do as instance is already created
  60062. };
  60063. DebugLayer.prototype.isVisible = function () {
  60064. if (!this._inspector) {
  60065. return false;
  60066. }
  60067. return true;
  60068. };
  60069. DebugLayer.prototype.hide = function () {
  60070. if (this._inspector) {
  60071. try {
  60072. this._inspector.dispose();
  60073. }
  60074. catch (e) {
  60075. // If the inspector has been removed directly from the inspector tool
  60076. }
  60077. this.onPropertyChangedObservable.clear();
  60078. this._inspector = null;
  60079. }
  60080. };
  60081. /**
  60082. *
  60083. * Launch the debugLayer.
  60084. *
  60085. * initialTab:
  60086. * | Value | Tab Name |
  60087. * | --- | --- |
  60088. * | 0 | Scene |
  60089. * | 1 | Console |
  60090. * | 2 | Stats |
  60091. * | 3 | Textures |
  60092. * | 4 | Mesh |
  60093. * | 5 | Light |
  60094. * | 6 | Material |
  60095. * | 7 | GLTF |
  60096. * | 8 | GUI |
  60097. * | 9 | Physics |
  60098. * | 10 | Camera |
  60099. * | 11 | Audio |
  60100. *
  60101. */
  60102. DebugLayer.prototype.show = function (config) {
  60103. if (config === void 0) { config = {}; }
  60104. if (typeof this.BJSINSPECTOR == 'undefined') {
  60105. // Load inspector and add it to the DOM
  60106. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60107. }
  60108. else {
  60109. // Otherwise creates the inspector
  60110. this._createInspector(config);
  60111. }
  60112. };
  60113. /**
  60114. * Gets the active tab
  60115. * @return the index of the active tab or -1 if the inspector is hidden
  60116. */
  60117. DebugLayer.prototype.getActiveTab = function () {
  60118. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60119. };
  60120. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60121. return DebugLayer;
  60122. }());
  60123. BABYLON.DebugLayer = DebugLayer;
  60124. })(BABYLON || (BABYLON = {}));
  60125. //# sourceMappingURL=babylon.debugLayer.js.map
  60126. var BABYLON;
  60127. (function (BABYLON) {
  60128. var Debug;
  60129. (function (Debug) {
  60130. /**
  60131. * Used to show the physics impostor around the specific mesh
  60132. */
  60133. var PhysicsViewer = /** @class */ (function () {
  60134. /**
  60135. * Creates a new PhysicsViewer
  60136. * @param scene defines the hosting scene
  60137. */
  60138. function PhysicsViewer(scene) {
  60139. /** @hidden */
  60140. this._impostors = [];
  60141. /** @hidden */
  60142. this._meshes = [];
  60143. /** @hidden */
  60144. this._numMeshes = 0;
  60145. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60146. var physicEngine = this._scene.getPhysicsEngine();
  60147. if (physicEngine) {
  60148. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60149. }
  60150. }
  60151. /** @hidden */
  60152. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60153. var plugin = this._physicsEnginePlugin;
  60154. for (var i = 0; i < this._numMeshes; i++) {
  60155. var impostor = this._impostors[i];
  60156. if (!impostor) {
  60157. continue;
  60158. }
  60159. if (impostor.isDisposed) {
  60160. this.hideImpostor(this._impostors[i--]);
  60161. }
  60162. else {
  60163. var mesh = this._meshes[i];
  60164. if (mesh && plugin) {
  60165. plugin.syncMeshWithImpostor(mesh, impostor);
  60166. }
  60167. }
  60168. }
  60169. };
  60170. /**
  60171. * Renders a specified physic impostor
  60172. * @param impostor defines the impostor to render
  60173. */
  60174. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60175. if (!this._scene) {
  60176. return;
  60177. }
  60178. for (var i = 0; i < this._numMeshes; i++) {
  60179. if (this._impostors[i] == impostor) {
  60180. return;
  60181. }
  60182. }
  60183. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60184. if (debugMesh) {
  60185. this._impostors[this._numMeshes] = impostor;
  60186. this._meshes[this._numMeshes] = debugMesh;
  60187. if (this._numMeshes === 0) {
  60188. this._renderFunction = this._updateDebugMeshes.bind(this);
  60189. this._scene.registerBeforeRender(this._renderFunction);
  60190. }
  60191. this._numMeshes++;
  60192. }
  60193. };
  60194. /**
  60195. * Hides a specified physic impostor
  60196. * @param impostor defines the impostor to hide
  60197. */
  60198. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60199. if (!impostor || !this._scene) {
  60200. return;
  60201. }
  60202. var removed = false;
  60203. for (var i = 0; i < this._numMeshes; i++) {
  60204. if (this._impostors[i] == impostor) {
  60205. var mesh = this._meshes[i];
  60206. if (!mesh) {
  60207. continue;
  60208. }
  60209. this._scene.removeMesh(mesh);
  60210. mesh.dispose();
  60211. this._numMeshes--;
  60212. if (this._numMeshes > 0) {
  60213. this._meshes[i] = this._meshes[this._numMeshes];
  60214. this._impostors[i] = this._impostors[this._numMeshes];
  60215. this._meshes[this._numMeshes] = null;
  60216. this._impostors[this._numMeshes] = null;
  60217. }
  60218. else {
  60219. this._meshes[0] = null;
  60220. this._impostors[0] = null;
  60221. }
  60222. removed = true;
  60223. break;
  60224. }
  60225. }
  60226. if (removed && this._numMeshes === 0) {
  60227. this._scene.unregisterBeforeRender(this._renderFunction);
  60228. }
  60229. };
  60230. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60231. if (!this._debugMaterial) {
  60232. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60233. this._debugMaterial.wireframe = true;
  60234. }
  60235. return this._debugMaterial;
  60236. };
  60237. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60238. if (!this._debugBoxMesh) {
  60239. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60240. this._debugBoxMesh.renderingGroupId = 1;
  60241. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60242. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60243. scene.removeMesh(this._debugBoxMesh);
  60244. }
  60245. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60246. };
  60247. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60248. if (!this._debugSphereMesh) {
  60249. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60250. this._debugSphereMesh.renderingGroupId = 1;
  60251. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60252. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60253. scene.removeMesh(this._debugSphereMesh);
  60254. }
  60255. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60256. };
  60257. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60258. var mesh = null;
  60259. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60260. mesh = this._getDebugBoxMesh(scene);
  60261. impostor.getBoxSizeToRef(mesh.scaling);
  60262. }
  60263. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60264. mesh = this._getDebugSphereMesh(scene);
  60265. var radius = impostor.getRadius();
  60266. mesh.scaling.x = radius * 2;
  60267. mesh.scaling.y = radius * 2;
  60268. mesh.scaling.z = radius * 2;
  60269. }
  60270. return mesh;
  60271. };
  60272. /** Releases all resources */
  60273. PhysicsViewer.prototype.dispose = function () {
  60274. for (var i = 0; i < this._numMeshes; i++) {
  60275. this.hideImpostor(this._impostors[i]);
  60276. }
  60277. if (this._debugBoxMesh) {
  60278. this._debugBoxMesh.dispose();
  60279. }
  60280. if (this._debugSphereMesh) {
  60281. this._debugSphereMesh.dispose();
  60282. }
  60283. if (this._debugMaterial) {
  60284. this._debugMaterial.dispose();
  60285. }
  60286. this._impostors.length = 0;
  60287. this._scene = null;
  60288. this._physicsEnginePlugin = null;
  60289. };
  60290. return PhysicsViewer;
  60291. }());
  60292. Debug.PhysicsViewer = PhysicsViewer;
  60293. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60294. })(BABYLON || (BABYLON = {}));
  60295. //# sourceMappingURL=babylon.physicsViewer.js.map
  60296. var BABYLON;
  60297. (function (BABYLON) {
  60298. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60299. get: function () {
  60300. return this._forceShowBoundingBoxes || false;
  60301. },
  60302. set: function (value) {
  60303. this._forceShowBoundingBoxes = value;
  60304. // Lazyly creates a BB renderer if needed.
  60305. if (value) {
  60306. this.getBoundingBoxRenderer();
  60307. }
  60308. },
  60309. enumerable: true,
  60310. configurable: true
  60311. });
  60312. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60313. if (!this._boundingBoxRenderer) {
  60314. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60315. }
  60316. return this._boundingBoxRenderer;
  60317. };
  60318. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60319. get: function () {
  60320. return this._showBoundingBox || false;
  60321. },
  60322. set: function (value) {
  60323. this._showBoundingBox = value;
  60324. // Lazyly creates a BB renderer if needed.
  60325. if (value) {
  60326. this.getScene().getBoundingBoxRenderer();
  60327. }
  60328. },
  60329. enumerable: true,
  60330. configurable: true
  60331. });
  60332. var BoundingBoxRenderer = /** @class */ (function () {
  60333. function BoundingBoxRenderer(scene) {
  60334. /**
  60335. * The component name helpfull to identify the component in the list of scene components.
  60336. */
  60337. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60338. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60339. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60340. this.showBackLines = true;
  60341. this.renderList = new BABYLON.SmartArray(32);
  60342. this._vertexBuffers = {};
  60343. this.scene = scene;
  60344. scene._addComponent(this);
  60345. }
  60346. /**
  60347. * Registers the component in a given scene
  60348. */
  60349. BoundingBoxRenderer.prototype.register = function () {
  60350. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60351. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60352. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60353. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60354. };
  60355. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60356. if (mesh.showSubMeshesBoundingBox) {
  60357. var boundingInfo = subMesh.getBoundingInfo();
  60358. if (boundingInfo !== null && boundingInfo !== undefined) {
  60359. this.renderList.push(boundingInfo.boundingBox);
  60360. }
  60361. }
  60362. };
  60363. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60364. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60365. var boundingInfo = sourceMesh.getBoundingInfo();
  60366. this.renderList.push(boundingInfo.boundingBox);
  60367. }
  60368. };
  60369. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60370. if (this._colorShader) {
  60371. return;
  60372. }
  60373. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60374. attributes: [BABYLON.VertexBuffer.PositionKind],
  60375. uniforms: ["world", "viewProjection", "color"]
  60376. });
  60377. var engine = this.scene.getEngine();
  60378. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60379. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60380. this._createIndexBuffer();
  60381. };
  60382. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60383. var engine = this.scene.getEngine();
  60384. 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]);
  60385. };
  60386. /**
  60387. * Rebuilds the elements related to this component in case of
  60388. * context lost for instance.
  60389. */
  60390. BoundingBoxRenderer.prototype.rebuild = function () {
  60391. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60392. if (vb) {
  60393. vb._rebuild();
  60394. }
  60395. this._createIndexBuffer();
  60396. };
  60397. BoundingBoxRenderer.prototype.reset = function () {
  60398. this.renderList.reset();
  60399. };
  60400. BoundingBoxRenderer.prototype.render = function () {
  60401. if (this.renderList.length === 0) {
  60402. return;
  60403. }
  60404. this._prepareRessources();
  60405. if (!this._colorShader.isReady()) {
  60406. return;
  60407. }
  60408. var engine = this.scene.getEngine();
  60409. engine.setDepthWrite(false);
  60410. this._colorShader._preBind();
  60411. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60412. var boundingBox = this.renderList.data[boundingBoxIndex];
  60413. var min = boundingBox.minimum;
  60414. var max = boundingBox.maximum;
  60415. var diff = max.subtract(min);
  60416. var median = min.add(diff.scale(0.5));
  60417. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60418. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60419. .multiply(boundingBox.getWorldMatrix());
  60420. // VBOs
  60421. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60422. if (this.showBackLines) {
  60423. // Back
  60424. engine.setDepthFunctionToGreaterOrEqual();
  60425. this.scene.resetCachedMaterial();
  60426. this._colorShader.setColor4("color", this.backColor.toColor4());
  60427. this._colorShader.bind(worldMatrix);
  60428. // Draw order
  60429. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60430. }
  60431. // Front
  60432. engine.setDepthFunctionToLess();
  60433. this.scene.resetCachedMaterial();
  60434. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60435. this._colorShader.bind(worldMatrix);
  60436. // Draw order
  60437. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60438. }
  60439. this._colorShader.unbind();
  60440. engine.setDepthFunctionToLessOrEqual();
  60441. engine.setDepthWrite(true);
  60442. };
  60443. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60444. this._prepareRessources();
  60445. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60446. return;
  60447. }
  60448. var engine = this.scene.getEngine();
  60449. engine.setDepthWrite(false);
  60450. engine.setColorWrite(false);
  60451. this._colorShader._preBind();
  60452. var boundingBox = mesh._boundingInfo.boundingBox;
  60453. var min = boundingBox.minimum;
  60454. var max = boundingBox.maximum;
  60455. var diff = max.subtract(min);
  60456. var median = min.add(diff.scale(0.5));
  60457. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60458. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60459. .multiply(boundingBox.getWorldMatrix());
  60460. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60461. engine.setDepthFunctionToLess();
  60462. this.scene.resetCachedMaterial();
  60463. this._colorShader.bind(worldMatrix);
  60464. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60465. this._colorShader.unbind();
  60466. engine.setDepthFunctionToLessOrEqual();
  60467. engine.setDepthWrite(true);
  60468. engine.setColorWrite(true);
  60469. };
  60470. BoundingBoxRenderer.prototype.dispose = function () {
  60471. if (!this._colorShader) {
  60472. return;
  60473. }
  60474. this.renderList.dispose();
  60475. this._colorShader.dispose();
  60476. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60477. if (buffer) {
  60478. buffer.dispose();
  60479. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60480. }
  60481. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60482. };
  60483. return BoundingBoxRenderer;
  60484. }());
  60485. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60486. })(BABYLON || (BABYLON = {}));
  60487. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60488. var BABYLON;
  60489. (function (BABYLON) {
  60490. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60491. return this._gl.createTransformFeedback();
  60492. };
  60493. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60494. this._gl.deleteTransformFeedback(value);
  60495. };
  60496. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60497. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60498. };
  60499. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60500. if (usePoints === void 0) { usePoints = true; }
  60501. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60502. };
  60503. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60504. this._gl.endTransformFeedback();
  60505. };
  60506. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60507. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60508. };
  60509. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60510. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60511. };
  60512. })(BABYLON || (BABYLON = {}));
  60513. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60514. var BABYLON;
  60515. (function (BABYLON) {
  60516. /**
  60517. * This represents a GPU particle system in Babylon
  60518. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60519. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60520. */
  60521. var GPUParticleSystem = /** @class */ (function (_super) {
  60522. __extends(GPUParticleSystem, _super);
  60523. /**
  60524. * Instantiates a GPU particle system.
  60525. * 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.
  60526. * @param name The name of the particle system
  60527. * @param options The options used to create the system
  60528. * @param scene The scene the particle system belongs to
  60529. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60530. */
  60531. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60532. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60533. var _this = _super.call(this, name) || this;
  60534. /**
  60535. * The layer mask we are rendering the particles through.
  60536. */
  60537. _this.layerMask = 0x0FFFFFFF;
  60538. _this._accumulatedCount = 0;
  60539. _this._targetIndex = 0;
  60540. _this._currentRenderId = -1;
  60541. _this._started = false;
  60542. _this._stopped = false;
  60543. _this._timeDelta = 0;
  60544. _this._attributesStrideSize = 21;
  60545. _this._actualFrame = 0;
  60546. _this._rawTextureWidth = 256;
  60547. /**
  60548. * An event triggered when the system is disposed.
  60549. */
  60550. _this.onDisposeObservable = new BABYLON.Observable();
  60551. /**
  60552. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60553. * to override the particles.
  60554. */
  60555. _this.forceDepthWrite = false;
  60556. _this._preWarmDone = false;
  60557. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60558. // Setup the default processing configuration to the scene.
  60559. _this._attachImageProcessingConfiguration(null);
  60560. _this._engine = _this._scene.getEngine();
  60561. if (!options.randomTextureSize) {
  60562. delete options.randomTextureSize;
  60563. }
  60564. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60565. var optionsAsNumber = options;
  60566. if (isFinite(optionsAsNumber)) {
  60567. fullOptions.capacity = optionsAsNumber;
  60568. }
  60569. _this._capacity = fullOptions.capacity;
  60570. _this._activeCount = fullOptions.capacity;
  60571. _this._currentActiveCount = 0;
  60572. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60573. _this._scene.particleSystems.push(_this);
  60574. _this._updateEffectOptions = {
  60575. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60576. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60577. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60578. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60579. uniformBuffersNames: [],
  60580. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60581. defines: "",
  60582. fallbacks: null,
  60583. onCompiled: null,
  60584. onError: null,
  60585. indexParameters: null,
  60586. maxSimultaneousLights: 0,
  60587. transformFeedbackVaryings: []
  60588. };
  60589. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60590. // Random data
  60591. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60592. var d = [];
  60593. for (var i = 0; i < maxTextureSize; ++i) {
  60594. d.push(Math.random());
  60595. d.push(Math.random());
  60596. d.push(Math.random());
  60597. d.push(Math.random());
  60598. }
  60599. _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);
  60600. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60601. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60602. d = [];
  60603. for (var i = 0; i < maxTextureSize; ++i) {
  60604. d.push(Math.random());
  60605. d.push(Math.random());
  60606. d.push(Math.random());
  60607. d.push(Math.random());
  60608. }
  60609. _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);
  60610. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60611. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60612. _this._randomTextureSize = maxTextureSize;
  60613. return _this;
  60614. }
  60615. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60616. /**
  60617. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60618. */
  60619. get: function () {
  60620. if (!BABYLON.Engine.LastCreatedEngine) {
  60621. return false;
  60622. }
  60623. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60624. },
  60625. enumerable: true,
  60626. configurable: true
  60627. });
  60628. /**
  60629. * Gets the maximum number of particles active at the same time.
  60630. * @returns The max number of active particles.
  60631. */
  60632. GPUParticleSystem.prototype.getCapacity = function () {
  60633. return this._capacity;
  60634. };
  60635. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60636. /**
  60637. * Gets or set the number of active particles
  60638. */
  60639. get: function () {
  60640. return this._activeCount;
  60641. },
  60642. set: function (value) {
  60643. this._activeCount = Math.min(value, this._capacity);
  60644. },
  60645. enumerable: true,
  60646. configurable: true
  60647. });
  60648. /**
  60649. * Is this system ready to be used/rendered
  60650. * @return true if the system is ready
  60651. */
  60652. GPUParticleSystem.prototype.isReady = function () {
  60653. if (!this._updateEffect) {
  60654. this._recreateUpdateEffect();
  60655. this._recreateRenderEffect();
  60656. return false;
  60657. }
  60658. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60659. return false;
  60660. }
  60661. return true;
  60662. };
  60663. /**
  60664. * Gets Wether the system has been started.
  60665. * @returns True if it has been started, otherwise false.
  60666. */
  60667. GPUParticleSystem.prototype.isStarted = function () {
  60668. return this._started;
  60669. };
  60670. /**
  60671. * Starts the particle system and begins to emit
  60672. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60673. */
  60674. GPUParticleSystem.prototype.start = function (delay) {
  60675. var _this = this;
  60676. if (delay === void 0) { delay = 0; }
  60677. if (delay) {
  60678. setTimeout(function () {
  60679. _this.start(0);
  60680. }, delay);
  60681. return;
  60682. }
  60683. this._started = true;
  60684. this._stopped = false;
  60685. this._preWarmDone = false;
  60686. };
  60687. /**
  60688. * Stops the particle system.
  60689. */
  60690. GPUParticleSystem.prototype.stop = function () {
  60691. this._stopped = true;
  60692. };
  60693. /**
  60694. * Remove all active particles
  60695. */
  60696. GPUParticleSystem.prototype.reset = function () {
  60697. this._releaseBuffers();
  60698. this._releaseVAOs();
  60699. this._currentActiveCount = 0;
  60700. this._targetIndex = 0;
  60701. };
  60702. /**
  60703. * Returns the string "GPUParticleSystem"
  60704. * @returns a string containing the class name
  60705. */
  60706. GPUParticleSystem.prototype.getClassName = function () {
  60707. return "GPUParticleSystem";
  60708. };
  60709. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60710. if (!gradients) {
  60711. return this;
  60712. }
  60713. var index = 0;
  60714. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60715. var valueGradient = gradients_1[_i];
  60716. if (valueGradient.gradient === gradient) {
  60717. gradients.splice(index, 1);
  60718. break;
  60719. }
  60720. index++;
  60721. }
  60722. if (texture) {
  60723. texture.dispose();
  60724. }
  60725. this._releaseBuffers();
  60726. return this;
  60727. };
  60728. /**
  60729. * Adds a new color gradient
  60730. * @param gradient defines the gradient to use (between 0 and 1)
  60731. * @param color defines the color to affect to the specified gradient
  60732. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60733. * @returns the current particle system
  60734. */
  60735. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60736. if (!this._colorGradients) {
  60737. this._colorGradients = [];
  60738. }
  60739. var colorGradient = new BABYLON.ColorGradient();
  60740. colorGradient.gradient = gradient;
  60741. colorGradient.color1 = color1;
  60742. this._colorGradients.push(colorGradient);
  60743. this._colorGradients.sort(function (a, b) {
  60744. if (a.gradient < b.gradient) {
  60745. return -1;
  60746. }
  60747. else if (a.gradient > b.gradient) {
  60748. return 1;
  60749. }
  60750. return 0;
  60751. });
  60752. if (this._colorGradientsTexture) {
  60753. this._colorGradientsTexture.dispose();
  60754. this._colorGradientsTexture = null;
  60755. }
  60756. this._releaseBuffers();
  60757. return this;
  60758. };
  60759. /**
  60760. * Remove a specific color gradient
  60761. * @param gradient defines the gradient to remove
  60762. * @returns the current particle system
  60763. */
  60764. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60765. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60766. this._colorGradientsTexture = null;
  60767. return this;
  60768. };
  60769. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60770. var valueGradient = new BABYLON.FactorGradient();
  60771. valueGradient.gradient = gradient;
  60772. valueGradient.factor1 = factor;
  60773. factorGradients.push(valueGradient);
  60774. factorGradients.sort(function (a, b) {
  60775. if (a.gradient < b.gradient) {
  60776. return -1;
  60777. }
  60778. else if (a.gradient > b.gradient) {
  60779. return 1;
  60780. }
  60781. return 0;
  60782. });
  60783. this._releaseBuffers();
  60784. };
  60785. /**
  60786. * Adds a new size gradient
  60787. * @param gradient defines the gradient to use (between 0 and 1)
  60788. * @param factor defines the size factor to affect to the specified gradient
  60789. * @returns the current particle system
  60790. */
  60791. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60792. if (!this._sizeGradients) {
  60793. this._sizeGradients = [];
  60794. }
  60795. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60796. if (this._sizeGradientsTexture) {
  60797. this._sizeGradientsTexture.dispose();
  60798. this._sizeGradientsTexture = null;
  60799. }
  60800. this._releaseBuffers();
  60801. return this;
  60802. };
  60803. /**
  60804. * Remove a specific size gradient
  60805. * @param gradient defines the gradient to remove
  60806. * @returns the current particle system
  60807. */
  60808. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60809. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60810. this._sizeGradientsTexture = null;
  60811. return this;
  60812. };
  60813. /**
  60814. * Adds a new angular speed gradient
  60815. * @param gradient defines the gradient to use (between 0 and 1)
  60816. * @param factor defines the angular speed to affect to the specified gradient
  60817. * @returns the current particle system
  60818. */
  60819. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60820. if (!this._angularSpeedGradients) {
  60821. this._angularSpeedGradients = [];
  60822. }
  60823. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60824. if (this._angularSpeedGradientsTexture) {
  60825. this._angularSpeedGradientsTexture.dispose();
  60826. this._angularSpeedGradientsTexture = null;
  60827. }
  60828. this._releaseBuffers();
  60829. return this;
  60830. };
  60831. /**
  60832. * Remove a specific angular speed gradient
  60833. * @param gradient defines the gradient to remove
  60834. * @returns the current particle system
  60835. */
  60836. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60837. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60838. this._angularSpeedGradientsTexture = null;
  60839. return this;
  60840. };
  60841. /**
  60842. * Adds a new velocity gradient
  60843. * @param gradient defines the gradient to use (between 0 and 1)
  60844. * @param factor defines the velocity to affect to the specified gradient
  60845. * @returns the current particle system
  60846. */
  60847. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60848. if (!this._velocityGradients) {
  60849. this._velocityGradients = [];
  60850. }
  60851. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60852. if (this._velocityGradientsTexture) {
  60853. this._velocityGradientsTexture.dispose();
  60854. this._velocityGradientsTexture = null;
  60855. }
  60856. this._releaseBuffers();
  60857. return this;
  60858. };
  60859. /**
  60860. * Remove a specific velocity gradient
  60861. * @param gradient defines the gradient to remove
  60862. * @returns the current particle system
  60863. */
  60864. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60865. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60866. this._velocityGradientsTexture = null;
  60867. return this;
  60868. };
  60869. /**
  60870. * Adds a new limit velocity gradient
  60871. * @param gradient defines the gradient to use (between 0 and 1)
  60872. * @param factor defines the limit velocity value to affect to the specified gradient
  60873. * @returns the current particle system
  60874. */
  60875. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  60876. if (!this._limitVelocityGradients) {
  60877. this._limitVelocityGradients = [];
  60878. }
  60879. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  60880. if (this._limitVelocityGradientsTexture) {
  60881. this._limitVelocityGradientsTexture.dispose();
  60882. this._limitVelocityGradientsTexture = null;
  60883. }
  60884. this._releaseBuffers();
  60885. return this;
  60886. };
  60887. /**
  60888. * Remove a specific limit velocity gradient
  60889. * @param gradient defines the gradient to remove
  60890. * @returns the current particle system
  60891. */
  60892. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60893. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  60894. this._limitVelocityGradientsTexture = null;
  60895. return this;
  60896. };
  60897. GPUParticleSystem.prototype._reset = function () {
  60898. this._releaseBuffers();
  60899. };
  60900. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60901. var updateVertexBuffers = {};
  60902. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60903. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60904. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60905. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60906. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60907. var offset = 12;
  60908. if (!this._colorGradientsTexture) {
  60909. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60910. offset += 4;
  60911. }
  60912. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60913. offset += 3;
  60914. if (!this._isBillboardBased) {
  60915. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60916. offset += 3;
  60917. }
  60918. if (this._angularSpeedGradientsTexture) {
  60919. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60920. offset += 1;
  60921. }
  60922. else {
  60923. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60924. offset += 2;
  60925. }
  60926. if (this._isAnimationSheetEnabled) {
  60927. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60928. offset += 1;
  60929. }
  60930. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60931. this._engine.bindArrayBuffer(null);
  60932. return vao;
  60933. };
  60934. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60935. var renderVertexBuffers = {};
  60936. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60937. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60938. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60939. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60940. var offset = 12;
  60941. if (!this._colorGradientsTexture) {
  60942. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60943. offset += 4;
  60944. }
  60945. offset += 3; // Direction
  60946. if (!this._isBillboardBased) {
  60947. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60948. offset += 3;
  60949. }
  60950. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60951. if (this._angularSpeedGradientsTexture) {
  60952. offset++;
  60953. }
  60954. else {
  60955. offset += 2;
  60956. }
  60957. if (this._isAnimationSheetEnabled) {
  60958. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60959. offset += 1;
  60960. }
  60961. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60962. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60963. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60964. this._engine.bindArrayBuffer(null);
  60965. return vao;
  60966. };
  60967. GPUParticleSystem.prototype._initialize = function (force) {
  60968. if (force === void 0) { force = false; }
  60969. if (this._buffer0 && !force) {
  60970. return;
  60971. }
  60972. var engine = this._scene.getEngine();
  60973. var data = new Array();
  60974. if (!this.isBillboardBased) {
  60975. this._attributesStrideSize += 3;
  60976. }
  60977. if (this._colorGradientsTexture) {
  60978. this._attributesStrideSize -= 4;
  60979. }
  60980. if (this._angularSpeedGradientsTexture) {
  60981. this._attributesStrideSize -= 1;
  60982. }
  60983. if (this._isAnimationSheetEnabled) {
  60984. this._attributesStrideSize += 1;
  60985. }
  60986. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60987. // position
  60988. data.push(0.0);
  60989. data.push(0.0);
  60990. data.push(0.0);
  60991. // Age and life
  60992. data.push(0.0); // create the particle as a dead one to create a new one at start
  60993. data.push(0.0);
  60994. // Seed
  60995. data.push(Math.random());
  60996. data.push(Math.random());
  60997. data.push(Math.random());
  60998. data.push(Math.random());
  60999. // Size
  61000. data.push(0.0);
  61001. data.push(0.0);
  61002. data.push(0.0);
  61003. if (!this._colorGradientsTexture) {
  61004. // color
  61005. data.push(0.0);
  61006. data.push(0.0);
  61007. data.push(0.0);
  61008. data.push(0.0);
  61009. }
  61010. // direction
  61011. data.push(0.0);
  61012. data.push(0.0);
  61013. data.push(0.0);
  61014. if (!this.isBillboardBased) {
  61015. // initialDirection
  61016. data.push(0.0);
  61017. data.push(0.0);
  61018. data.push(0.0);
  61019. }
  61020. // angle
  61021. data.push(0.0);
  61022. if (!this._angularSpeedGradientsTexture) {
  61023. data.push(0.0);
  61024. }
  61025. if (this._isAnimationSheetEnabled) {
  61026. data.push(0.0);
  61027. }
  61028. }
  61029. // Sprite data
  61030. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61031. -0.5, 0.5, 0, 1,
  61032. -0.5, -0.5, 0, 0,
  61033. 0.5, -0.5, 1, 0]);
  61034. // Buffers
  61035. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61036. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61037. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61038. // Update VAO
  61039. this._updateVAO = [];
  61040. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61041. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61042. // Render VAO
  61043. this._renderVAO = [];
  61044. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61045. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61046. // Links
  61047. this._sourceBuffer = this._buffer0;
  61048. this._targetBuffer = this._buffer1;
  61049. };
  61050. /** @hidden */
  61051. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61052. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61053. if (this._isBillboardBased) {
  61054. defines += "\n#define BILLBOARD";
  61055. }
  61056. if (this._colorGradientsTexture) {
  61057. defines += "\n#define COLORGRADIENTS";
  61058. }
  61059. if (this._sizeGradientsTexture) {
  61060. defines += "\n#define SIZEGRADIENTS";
  61061. }
  61062. if (this._angularSpeedGradientsTexture) {
  61063. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61064. }
  61065. if (this._velocityGradientsTexture) {
  61066. defines += "\n#define VELOCITYGRADIENTS";
  61067. }
  61068. if (this.isAnimationSheetEnabled) {
  61069. defines += "\n#define ANIMATESHEET";
  61070. }
  61071. if (this.noiseTexture) {
  61072. defines += "\n#define NOISE";
  61073. }
  61074. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61075. return;
  61076. }
  61077. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61078. if (!this._colorGradientsTexture) {
  61079. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61080. }
  61081. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61082. if (!this._isBillboardBased) {
  61083. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61084. }
  61085. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61086. if (this.isAnimationSheetEnabled) {
  61087. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61088. }
  61089. this._updateEffectOptions.defines = defines;
  61090. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61091. };
  61092. /** @hidden */
  61093. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61094. var defines = "";
  61095. if (this._scene.clipPlane) {
  61096. defines = "\n#define CLIPPLANE";
  61097. }
  61098. if (this._scene.clipPlane2) {
  61099. defines = "\n#define CLIPPLANE2";
  61100. }
  61101. if (this._scene.clipPlane3) {
  61102. defines = "\n#define CLIPPLANE3";
  61103. }
  61104. if (this._scene.clipPlane4) {
  61105. defines = "\n#define CLIPPLANE4";
  61106. }
  61107. if (this._isBillboardBased) {
  61108. defines += "\n#define BILLBOARD";
  61109. switch (this.billboardMode) {
  61110. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61111. defines += "\n#define BILLBOARDY";
  61112. break;
  61113. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61114. default:
  61115. break;
  61116. }
  61117. }
  61118. if (this._colorGradientsTexture) {
  61119. defines += "\n#define COLORGRADIENTS";
  61120. }
  61121. if (this.isAnimationSheetEnabled) {
  61122. defines += "\n#define ANIMATESHEET";
  61123. }
  61124. if (this._imageProcessingConfiguration) {
  61125. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61126. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61127. }
  61128. if (this._renderEffect && this._renderEffect.defines === defines) {
  61129. return;
  61130. }
  61131. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61132. var samplers = ["textureSampler", "colorGradientSampler"];
  61133. if (BABYLON.ImageProcessingConfiguration) {
  61134. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61135. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61136. }
  61137. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61138. };
  61139. /**
  61140. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61141. * @param preWarm defines if we are in the pre-warmimg phase
  61142. */
  61143. GPUParticleSystem.prototype.animate = function (preWarm) {
  61144. if (preWarm === void 0) { preWarm = false; }
  61145. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61146. this._actualFrame += this._timeDelta;
  61147. if (!this._stopped) {
  61148. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61149. this.stop();
  61150. }
  61151. }
  61152. };
  61153. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61154. var texture = this[textureName];
  61155. if (!factorGradients || !factorGradients.length || texture) {
  61156. return;
  61157. }
  61158. var data = new Float32Array(this._rawTextureWidth);
  61159. for (var x = 0; x < this._rawTextureWidth; x++) {
  61160. var ratio = x / this._rawTextureWidth;
  61161. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61162. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61163. });
  61164. }
  61165. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61166. };
  61167. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61168. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61169. };
  61170. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61171. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61172. };
  61173. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61174. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61175. };
  61176. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61177. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61178. return;
  61179. }
  61180. var data = new Uint8Array(this._rawTextureWidth * 4);
  61181. var tmpColor = BABYLON.Tmp.Color4[0];
  61182. for (var x = 0; x < this._rawTextureWidth; x++) {
  61183. var ratio = x / this._rawTextureWidth;
  61184. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61185. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61186. data[x * 4] = tmpColor.r * 255;
  61187. data[x * 4 + 1] = tmpColor.g * 255;
  61188. data[x * 4 + 2] = tmpColor.b * 255;
  61189. data[x * 4 + 3] = tmpColor.a * 255;
  61190. });
  61191. }
  61192. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61193. };
  61194. /**
  61195. * Renders the particle system in its current state
  61196. * @param preWarm defines if the system should only update the particles but not render them
  61197. * @returns the current number of particles
  61198. */
  61199. GPUParticleSystem.prototype.render = function (preWarm) {
  61200. if (preWarm === void 0) { preWarm = false; }
  61201. if (!this._started) {
  61202. return 0;
  61203. }
  61204. this._createColorGradientTexture();
  61205. this._createSizeGradientTexture();
  61206. this._createAngularSpeedGradientTexture();
  61207. this._createVelocityGradientTexture();
  61208. this._recreateUpdateEffect();
  61209. this._recreateRenderEffect();
  61210. if (!this.isReady()) {
  61211. return 0;
  61212. }
  61213. if (!preWarm) {
  61214. if (!this._preWarmDone && this.preWarmCycles) {
  61215. for (var index = 0; index < this.preWarmCycles; index++) {
  61216. this.animate(true);
  61217. this.render(true);
  61218. }
  61219. this._preWarmDone = true;
  61220. }
  61221. if (this._currentRenderId === this._scene.getRenderId()) {
  61222. return 0;
  61223. }
  61224. this._currentRenderId = this._scene.getRenderId();
  61225. }
  61226. // Get everything ready to render
  61227. this._initialize();
  61228. this._accumulatedCount += this.emitRate * this._timeDelta;
  61229. if (this._accumulatedCount > 1) {
  61230. var intPart = this._accumulatedCount | 0;
  61231. this._accumulatedCount -= intPart;
  61232. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61233. }
  61234. if (!this._currentActiveCount) {
  61235. return 0;
  61236. }
  61237. // Enable update effect
  61238. this._engine.enableEffect(this._updateEffect);
  61239. this._engine.setState(false);
  61240. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61241. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61242. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61243. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61244. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61245. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61246. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61247. if (!this._colorGradientsTexture) {
  61248. this._updateEffect.setDirectColor4("color1", this.color1);
  61249. this._updateEffect.setDirectColor4("color2", this.color2);
  61250. }
  61251. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61252. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61253. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61254. this._updateEffect.setVector3("gravity", this.gravity);
  61255. if (this._sizeGradientsTexture) {
  61256. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61257. }
  61258. if (this._angularSpeedGradientsTexture) {
  61259. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61260. }
  61261. if (this._velocityGradientsTexture) {
  61262. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61263. }
  61264. if (this.particleEmitterType) {
  61265. this.particleEmitterType.applyToShader(this._updateEffect);
  61266. }
  61267. if (this._isAnimationSheetEnabled) {
  61268. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61269. }
  61270. if (this.noiseTexture) {
  61271. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61272. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61273. }
  61274. var emitterWM;
  61275. if (this.emitter.position) {
  61276. var emitterMesh = this.emitter;
  61277. emitterWM = emitterMesh.getWorldMatrix();
  61278. }
  61279. else {
  61280. var emitterPosition = this.emitter;
  61281. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61282. }
  61283. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61284. // Bind source VAO
  61285. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61286. // Update
  61287. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61288. this._engine.setRasterizerState(false);
  61289. this._engine.beginTransformFeedback(true);
  61290. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61291. this._engine.endTransformFeedback();
  61292. this._engine.setRasterizerState(true);
  61293. this._engine.bindTransformFeedbackBuffer(null);
  61294. if (!preWarm) {
  61295. // Enable render effect
  61296. this._engine.enableEffect(this._renderEffect);
  61297. var viewMatrix = this._scene.getViewMatrix();
  61298. this._renderEffect.setMatrix("view", viewMatrix);
  61299. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61300. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61301. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61302. if (this._colorGradientsTexture) {
  61303. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61304. }
  61305. else {
  61306. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61307. }
  61308. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61309. var baseSize = this.particleTexture.getBaseSize();
  61310. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61311. }
  61312. if (this._isBillboardBased) {
  61313. var camera = this._scene.activeCamera;
  61314. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61315. }
  61316. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61317. var invView = viewMatrix.clone();
  61318. invView.invert();
  61319. this._renderEffect.setMatrix("invView", invView);
  61320. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61321. }
  61322. // image processing
  61323. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61324. this._imageProcessingConfiguration.bind(this._renderEffect);
  61325. }
  61326. // Draw order
  61327. switch (this.blendMode) {
  61328. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61329. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61330. break;
  61331. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61332. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61333. break;
  61334. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61335. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61336. break;
  61337. }
  61338. if (this.forceDepthWrite) {
  61339. this._engine.setDepthWrite(true);
  61340. }
  61341. // Bind source VAO
  61342. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61343. // Render
  61344. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61345. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61346. }
  61347. // Switch VAOs
  61348. this._targetIndex++;
  61349. if (this._targetIndex === 2) {
  61350. this._targetIndex = 0;
  61351. }
  61352. // Switch buffers
  61353. var tmpBuffer = this._sourceBuffer;
  61354. this._sourceBuffer = this._targetBuffer;
  61355. this._targetBuffer = tmpBuffer;
  61356. return this._currentActiveCount;
  61357. };
  61358. /**
  61359. * Rebuilds the particle system
  61360. */
  61361. GPUParticleSystem.prototype.rebuild = function () {
  61362. this._initialize(true);
  61363. };
  61364. GPUParticleSystem.prototype._releaseBuffers = function () {
  61365. if (this._buffer0) {
  61366. this._buffer0.dispose();
  61367. this._buffer0 = null;
  61368. }
  61369. if (this._buffer1) {
  61370. this._buffer1.dispose();
  61371. this._buffer1 = null;
  61372. }
  61373. if (this._spriteBuffer) {
  61374. this._spriteBuffer.dispose();
  61375. this._spriteBuffer = null;
  61376. }
  61377. };
  61378. GPUParticleSystem.prototype._releaseVAOs = function () {
  61379. if (!this._updateVAO) {
  61380. return;
  61381. }
  61382. for (var index = 0; index < this._updateVAO.length; index++) {
  61383. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61384. }
  61385. this._updateVAO = [];
  61386. for (var index = 0; index < this._renderVAO.length; index++) {
  61387. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61388. }
  61389. this._renderVAO = [];
  61390. };
  61391. /**
  61392. * Disposes the particle system and free the associated resources
  61393. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61394. */
  61395. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61396. if (disposeTexture === void 0) { disposeTexture = true; }
  61397. var index = this._scene.particleSystems.indexOf(this);
  61398. if (index > -1) {
  61399. this._scene.particleSystems.splice(index, 1);
  61400. }
  61401. this._releaseBuffers();
  61402. this._releaseVAOs();
  61403. if (this._colorGradientsTexture) {
  61404. this._colorGradientsTexture.dispose();
  61405. this._colorGradientsTexture = null;
  61406. }
  61407. if (this._sizeGradientsTexture) {
  61408. this._sizeGradientsTexture.dispose();
  61409. this._sizeGradientsTexture = null;
  61410. }
  61411. if (this._angularSpeedGradientsTexture) {
  61412. this._angularSpeedGradientsTexture.dispose();
  61413. this._angularSpeedGradientsTexture = null;
  61414. }
  61415. if (this._velocityGradientsTexture) {
  61416. this._velocityGradientsTexture.dispose();
  61417. this._velocityGradientsTexture = null;
  61418. }
  61419. if (this._limitVelocityGradientsTexture) {
  61420. this._limitVelocityGradientsTexture.dispose();
  61421. this._limitVelocityGradientsTexture = null;
  61422. }
  61423. if (this._randomTexture) {
  61424. this._randomTexture.dispose();
  61425. this._randomTexture = null;
  61426. }
  61427. if (this._randomTexture2) {
  61428. this._randomTexture2.dispose();
  61429. this._randomTexture2 = null;
  61430. }
  61431. if (disposeTexture && this.particleTexture) {
  61432. this.particleTexture.dispose();
  61433. this.particleTexture = null;
  61434. }
  61435. if (disposeTexture && this.noiseTexture) {
  61436. this.noiseTexture.dispose();
  61437. this.noiseTexture = null;
  61438. }
  61439. // Callback
  61440. this.onDisposeObservable.notifyObservers(this);
  61441. this.onDisposeObservable.clear();
  61442. };
  61443. /**
  61444. * Clones the particle system.
  61445. * @param name The name of the cloned object
  61446. * @param newEmitter The new emitter to use
  61447. * @returns the cloned particle system
  61448. */
  61449. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61450. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61451. BABYLON.Tools.DeepCopy(this, result);
  61452. if (newEmitter === undefined) {
  61453. newEmitter = this.emitter;
  61454. }
  61455. result.emitter = newEmitter;
  61456. if (this.particleTexture) {
  61457. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61458. }
  61459. return result;
  61460. };
  61461. /**
  61462. * Serializes the particle system to a JSON object.
  61463. * @returns the JSON object
  61464. */
  61465. GPUParticleSystem.prototype.serialize = function () {
  61466. var serializationObject = {};
  61467. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61468. serializationObject.activeParticleCount = this.activeParticleCount;
  61469. return serializationObject;
  61470. };
  61471. /**
  61472. * Parses a JSON object to create a GPU particle system.
  61473. * @param parsedParticleSystem The JSON object to parse
  61474. * @param scene The scene to create the particle system in
  61475. * @param rootUrl The root url to use to load external dependencies like texture
  61476. * @returns the parsed GPU particle system
  61477. */
  61478. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61479. var name = parsedParticleSystem.name;
  61480. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61481. if (parsedParticleSystem.activeParticleCount) {
  61482. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61483. }
  61484. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61485. return particleSystem;
  61486. };
  61487. return GPUParticleSystem;
  61488. }(BABYLON.BaseParticleSystem));
  61489. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61490. })(BABYLON || (BABYLON = {}));
  61491. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61492. var BABYLON;
  61493. (function (BABYLON) {
  61494. /**
  61495. * Represents one particle of a solid particle system.
  61496. */
  61497. var SolidParticle = /** @class */ (function () {
  61498. /**
  61499. * Creates a Solid Particle object.
  61500. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61501. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61502. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61503. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61504. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61505. * @param shapeId (integer) is the model shape identifier in the SPS.
  61506. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61507. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61508. */
  61509. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61510. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61511. /**
  61512. * particle global index
  61513. */
  61514. this.idx = 0;
  61515. /**
  61516. * The color of the particle
  61517. */
  61518. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61519. /**
  61520. * The world space position of the particle.
  61521. */
  61522. this.position = BABYLON.Vector3.Zero();
  61523. /**
  61524. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61525. */
  61526. this.rotation = BABYLON.Vector3.Zero();
  61527. /**
  61528. * The scaling of the particle.
  61529. */
  61530. this.scaling = BABYLON.Vector3.One();
  61531. /**
  61532. * The uvs of the particle.
  61533. */
  61534. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61535. /**
  61536. * The current speed of the particle.
  61537. */
  61538. this.velocity = BABYLON.Vector3.Zero();
  61539. /**
  61540. * The pivot point in the particle local space.
  61541. */
  61542. this.pivot = BABYLON.Vector3.Zero();
  61543. /**
  61544. * Must the particle be translated from its pivot point in its local space ?
  61545. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61546. * Default : false
  61547. */
  61548. this.translateFromPivot = false;
  61549. /**
  61550. * Is the particle active or not ?
  61551. */
  61552. this.alive = true;
  61553. /**
  61554. * Is the particle visible or not ?
  61555. */
  61556. this.isVisible = true;
  61557. /**
  61558. * Index of this particle in the global "positions" array (Internal use)
  61559. * @hidden
  61560. */
  61561. this._pos = 0;
  61562. /**
  61563. * @hidden Index of this particle in the global "indices" array (Internal use)
  61564. */
  61565. this._ind = 0;
  61566. /**
  61567. * ModelShape id of this particle
  61568. */
  61569. this.shapeId = 0;
  61570. /**
  61571. * Index of the particle in its shape id (Internal use)
  61572. */
  61573. this.idxInShape = 0;
  61574. /**
  61575. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  61576. */
  61577. this._stillInvisible = false;
  61578. /**
  61579. * @hidden Last computed particle rotation matrix
  61580. */
  61581. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61582. /**
  61583. * Parent particle Id, if any.
  61584. * Default null.
  61585. */
  61586. this.parentId = null;
  61587. /**
  61588. * @hidden Internal global position in the SPS.
  61589. */
  61590. this._globalPosition = BABYLON.Vector3.Zero();
  61591. this.idx = particleIndex;
  61592. this._pos = positionIndex;
  61593. this._ind = indiceIndex;
  61594. this._model = model;
  61595. this.shapeId = shapeId;
  61596. this.idxInShape = idxInShape;
  61597. this._sps = sps;
  61598. if (modelBoundingInfo) {
  61599. this._modelBoundingInfo = modelBoundingInfo;
  61600. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61601. }
  61602. }
  61603. Object.defineProperty(SolidParticle.prototype, "scale", {
  61604. /**
  61605. * Legacy support, changed scale to scaling
  61606. */
  61607. get: function () {
  61608. return this.scaling;
  61609. },
  61610. /**
  61611. * Legacy support, changed scale to scaling
  61612. */
  61613. set: function (scale) {
  61614. this.scaling = scale;
  61615. },
  61616. enumerable: true,
  61617. configurable: true
  61618. });
  61619. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61620. /**
  61621. * Legacy support, changed quaternion to rotationQuaternion
  61622. */
  61623. get: function () {
  61624. return this.rotationQuaternion;
  61625. },
  61626. /**
  61627. * Legacy support, changed quaternion to rotationQuaternion
  61628. */
  61629. set: function (q) {
  61630. this.rotationQuaternion = q;
  61631. },
  61632. enumerable: true,
  61633. configurable: true
  61634. });
  61635. /**
  61636. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61637. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61638. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61639. * @returns true if it intersects
  61640. */
  61641. SolidParticle.prototype.intersectsMesh = function (target) {
  61642. if (!this._boundingInfo || !target._boundingInfo) {
  61643. return false;
  61644. }
  61645. if (this._sps._bSphereOnly) {
  61646. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61647. }
  61648. return this._boundingInfo.intersects(target._boundingInfo, false);
  61649. };
  61650. return SolidParticle;
  61651. }());
  61652. BABYLON.SolidParticle = SolidParticle;
  61653. /**
  61654. * Represents the shape of the model used by one particle of a solid particle system.
  61655. * SPS internal tool, don't use it manually.
  61656. */
  61657. var ModelShape = /** @class */ (function () {
  61658. /**
  61659. * 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.
  61660. * SPS internal tool, don't use it manually.
  61661. * @hidden
  61662. */
  61663. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61664. /**
  61665. * length of the shape in the model indices array (internal use)
  61666. * @hidden
  61667. */
  61668. this._indicesLength = 0;
  61669. this.shapeID = id;
  61670. this._shape = shape;
  61671. this._indicesLength = indicesLength;
  61672. this._shapeUV = shapeUV;
  61673. this._positionFunction = posFunction;
  61674. this._vertexFunction = vtxFunction;
  61675. }
  61676. return ModelShape;
  61677. }());
  61678. BABYLON.ModelShape = ModelShape;
  61679. /**
  61680. * Represents a Depth Sorted Particle in the solid particle system.
  61681. */
  61682. var DepthSortedParticle = /** @class */ (function () {
  61683. function DepthSortedParticle() {
  61684. /**
  61685. * Index of the particle in the "indices" array
  61686. */
  61687. this.ind = 0;
  61688. /**
  61689. * Length of the particle shape in the "indices" array
  61690. */
  61691. this.indicesLength = 0;
  61692. /**
  61693. * Squared distance from the particle to the camera
  61694. */
  61695. this.sqDistance = 0.0;
  61696. }
  61697. return DepthSortedParticle;
  61698. }());
  61699. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61700. })(BABYLON || (BABYLON = {}));
  61701. //# sourceMappingURL=babylon.solidParticle.js.map
  61702. var BABYLON;
  61703. (function (BABYLON) {
  61704. /**
  61705. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61706. *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.
  61707. * The SPS is also a particle system. It provides some methods to manage the particles.
  61708. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61709. *
  61710. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61711. */
  61712. var SolidParticleSystem = /** @class */ (function () {
  61713. /**
  61714. * Creates a SPS (Solid Particle System) object.
  61715. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61716. * @param scene (Scene) is the scene in which the SPS is added.
  61717. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61718. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61719. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61720. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61721. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61722. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61723. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61724. */
  61725. function SolidParticleSystem(name, scene, options) {
  61726. /**
  61727. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61728. * Example : var p = SPS.particles[i];
  61729. */
  61730. this.particles = new Array();
  61731. /**
  61732. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61733. */
  61734. this.nbParticles = 0;
  61735. /**
  61736. * If the particles must ever face the camera (default false). Useful for planar particles.
  61737. */
  61738. this.billboard = false;
  61739. /**
  61740. * Recompute normals when adding a shape
  61741. */
  61742. this.recomputeNormals = true;
  61743. /**
  61744. * This a counter ofr your own usage. It's not set by any SPS functions.
  61745. */
  61746. this.counter = 0;
  61747. /**
  61748. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61749. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61750. */
  61751. this.vars = {};
  61752. /**
  61753. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61754. * @hidden
  61755. */
  61756. this._bSphereOnly = false;
  61757. /**
  61758. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61759. * @hidden
  61760. */
  61761. this._bSphereRadiusFactor = 1.0;
  61762. this._positions = new Array();
  61763. this._indices = new Array();
  61764. this._normals = new Array();
  61765. this._colors = new Array();
  61766. this._uvs = new Array();
  61767. this._index = 0; // indices index
  61768. this._updatable = true;
  61769. this._pickable = false;
  61770. this._isVisibilityBoxLocked = false;
  61771. this._alwaysVisible = false;
  61772. this._depthSort = false;
  61773. this._shapeCounter = 0;
  61774. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  61775. this._color = new BABYLON.Color4(0, 0, 0, 0);
  61776. this._computeParticleColor = true;
  61777. this._computeParticleTexture = true;
  61778. this._computeParticleRotation = true;
  61779. this._computeParticleVertex = false;
  61780. this._computeBoundingBox = false;
  61781. this._depthSortParticles = true;
  61782. this._cam_axisZ = BABYLON.Vector3.Zero();
  61783. this._cam_axisY = BABYLON.Vector3.Zero();
  61784. this._cam_axisX = BABYLON.Vector3.Zero();
  61785. this._axisZ = BABYLON.Axis.Z;
  61786. this._camDir = BABYLON.Vector3.Zero();
  61787. this._camInvertedPosition = BABYLON.Vector3.Zero();
  61788. this._rotMatrix = new BABYLON.Matrix();
  61789. this._invertMatrix = new BABYLON.Matrix();
  61790. this._rotated = BABYLON.Vector3.Zero();
  61791. this._quaternion = new BABYLON.Quaternion();
  61792. this._vertex = BABYLON.Vector3.Zero();
  61793. this._normal = BABYLON.Vector3.Zero();
  61794. this._yaw = 0.0;
  61795. this._pitch = 0.0;
  61796. this._roll = 0.0;
  61797. this._halfroll = 0.0;
  61798. this._halfpitch = 0.0;
  61799. this._halfyaw = 0.0;
  61800. this._sinRoll = 0.0;
  61801. this._cosRoll = 0.0;
  61802. this._sinPitch = 0.0;
  61803. this._cosPitch = 0.0;
  61804. this._sinYaw = 0.0;
  61805. this._cosYaw = 0.0;
  61806. this._mustUnrotateFixedNormals = false;
  61807. this._minimum = BABYLON.Vector3.Zero();
  61808. this._maximum = BABYLON.Vector3.Zero();
  61809. this._minBbox = BABYLON.Vector3.Zero();
  61810. this._maxBbox = BABYLON.Vector3.Zero();
  61811. this._particlesIntersect = false;
  61812. this._depthSortFunction = function (p1, p2) {
  61813. return (p2.sqDistance - p1.sqDistance);
  61814. };
  61815. this._needs32Bits = false;
  61816. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  61817. this._scaledPivot = BABYLON.Vector3.Zero();
  61818. this._particleHasParent = false;
  61819. this.name = name;
  61820. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61821. this._camera = scene.activeCamera;
  61822. this._pickable = options ? options.isPickable : false;
  61823. this._depthSort = options ? options.enableDepthSort : false;
  61824. this._particlesIntersect = options ? options.particleIntersection : false;
  61825. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  61826. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61827. if (options && options.updatable !== undefined) {
  61828. this._updatable = options.updatable;
  61829. }
  61830. else {
  61831. this._updatable = true;
  61832. }
  61833. if (this._pickable) {
  61834. this.pickedParticles = [];
  61835. }
  61836. if (this._depthSort) {
  61837. this.depthSortedParticles = [];
  61838. }
  61839. }
  61840. /**
  61841. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61842. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61843. * @returns the created mesh
  61844. */
  61845. SolidParticleSystem.prototype.buildMesh = function () {
  61846. if (this.nbParticles === 0) {
  61847. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61848. this.addShape(triangle, 1);
  61849. triangle.dispose();
  61850. }
  61851. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61852. this._positions32 = new Float32Array(this._positions);
  61853. this._uvs32 = new Float32Array(this._uvs);
  61854. this._colors32 = new Float32Array(this._colors);
  61855. if (this.recomputeNormals) {
  61856. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61857. }
  61858. this._normals32 = new Float32Array(this._normals);
  61859. this._fixedNormal32 = new Float32Array(this._normals);
  61860. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61861. this._unrotateFixedNormals();
  61862. }
  61863. var vertexData = new BABYLON.VertexData();
  61864. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61865. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61866. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61867. if (this._uvs32.length > 0) {
  61868. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61869. }
  61870. if (this._colors32.length > 0) {
  61871. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61872. }
  61873. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61874. vertexData.applyToMesh(mesh, this._updatable);
  61875. this.mesh = mesh;
  61876. this.mesh.isPickable = this._pickable;
  61877. // free memory
  61878. if (!this._depthSort) {
  61879. this._indices = null;
  61880. }
  61881. this._positions = null;
  61882. this._normals = null;
  61883. this._uvs = null;
  61884. this._colors = null;
  61885. if (!this._updatable) {
  61886. this.particles.length = 0;
  61887. }
  61888. return mesh;
  61889. };
  61890. /**
  61891. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61892. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61893. * Thus the particles generated from `digest()` have their property `position` set yet.
  61894. * @param mesh ( Mesh ) is the mesh to be digested
  61895. * @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
  61896. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61897. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61898. * @returns the current SPS
  61899. */
  61900. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61901. var size = (options && options.facetNb) || 1;
  61902. var number = (options && options.number) || 0;
  61903. var delta = (options && options.delta) || 0;
  61904. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61905. var meshInd = mesh.getIndices();
  61906. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61907. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61908. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61909. var f = 0; // facet counter
  61910. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61911. // compute size from number
  61912. if (number) {
  61913. number = (number > totalFacets) ? totalFacets : number;
  61914. size = Math.round(totalFacets / number);
  61915. delta = 0;
  61916. }
  61917. else {
  61918. size = (size > totalFacets) ? totalFacets : size;
  61919. }
  61920. var facetPos = []; // submesh positions
  61921. var facetInd = []; // submesh indices
  61922. var facetUV = []; // submesh UV
  61923. var facetCol = []; // submesh colors
  61924. var barycenter = BABYLON.Vector3.Zero();
  61925. var sizeO = size;
  61926. while (f < totalFacets) {
  61927. size = sizeO + Math.floor((1 + delta) * Math.random());
  61928. if (f > totalFacets - size) {
  61929. size = totalFacets - f;
  61930. }
  61931. // reset temp arrays
  61932. facetPos.length = 0;
  61933. facetInd.length = 0;
  61934. facetUV.length = 0;
  61935. facetCol.length = 0;
  61936. // iterate over "size" facets
  61937. var fi = 0;
  61938. for (var j = f * 3; j < (f + size) * 3; j++) {
  61939. facetInd.push(fi);
  61940. var i = meshInd[j];
  61941. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61942. if (meshUV) {
  61943. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61944. }
  61945. if (meshCol) {
  61946. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61947. }
  61948. fi++;
  61949. }
  61950. // create a model shape for each single particle
  61951. var idx = this.nbParticles;
  61952. var shape = this._posToShape(facetPos);
  61953. var shapeUV = this._uvsToShapeUV(facetUV);
  61954. // compute the barycenter of the shape
  61955. var v;
  61956. for (v = 0; v < shape.length; v++) {
  61957. barycenter.addInPlace(shape[v]);
  61958. }
  61959. barycenter.scaleInPlace(1 / shape.length);
  61960. // shift the shape from its barycenter to the origin
  61961. for (v = 0; v < shape.length; v++) {
  61962. shape[v].subtractInPlace(barycenter);
  61963. }
  61964. var bInfo;
  61965. if (this._particlesIntersect) {
  61966. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61967. }
  61968. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61969. // add the particle in the SPS
  61970. var currentPos = this._positions.length;
  61971. var currentInd = this._indices.length;
  61972. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61973. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61974. // initialize the particle position
  61975. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61976. this._index += shape.length;
  61977. idx++;
  61978. this.nbParticles++;
  61979. this._shapeCounter++;
  61980. f += size;
  61981. }
  61982. return this;
  61983. };
  61984. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61985. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61986. var index = 0;
  61987. var idx = 0;
  61988. for (var p = 0; p < this.particles.length; p++) {
  61989. this._particle = this.particles[p];
  61990. this._shape = this._particle._model._shape;
  61991. if (this._particle.rotationQuaternion) {
  61992. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61993. }
  61994. else {
  61995. this._yaw = this._particle.rotation.y;
  61996. this._pitch = this._particle.rotation.x;
  61997. this._roll = this._particle.rotation.z;
  61998. this._quaternionRotationYPR();
  61999. }
  62000. this._quaternionToRotationMatrix();
  62001. this._rotMatrix.invertToRef(this._invertMatrix);
  62002. for (var pt = 0; pt < this._shape.length; pt++) {
  62003. idx = index + pt * 3;
  62004. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62005. this._fixedNormal32[idx] = this._normal.x;
  62006. this._fixedNormal32[idx + 1] = this._normal.y;
  62007. this._fixedNormal32[idx + 2] = this._normal.z;
  62008. }
  62009. index = idx + 3;
  62010. }
  62011. };
  62012. //reset copy
  62013. SolidParticleSystem.prototype._resetCopy = function () {
  62014. this._copy.position.x = 0;
  62015. this._copy.position.y = 0;
  62016. this._copy.position.z = 0;
  62017. this._copy.rotation.x = 0;
  62018. this._copy.rotation.y = 0;
  62019. this._copy.rotation.z = 0;
  62020. this._copy.rotationQuaternion = null;
  62021. this._copy.scaling.x = 1.0;
  62022. this._copy.scaling.y = 1.0;
  62023. this._copy.scaling.z = 1.0;
  62024. this._copy.uvs.x = 0;
  62025. this._copy.uvs.y = 0;
  62026. this._copy.uvs.z = 1.0;
  62027. this._copy.uvs.w = 1.0;
  62028. this._copy.color = null;
  62029. this._copy.translateFromPivot = false;
  62030. };
  62031. // _meshBuilder : inserts the shape model in the global SPS mesh
  62032. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62033. var i;
  62034. var u = 0;
  62035. var c = 0;
  62036. var n = 0;
  62037. this._resetCopy();
  62038. if (options && options.positionFunction) { // call to custom positionFunction
  62039. options.positionFunction(this._copy, idx, idxInShape);
  62040. this._mustUnrotateFixedNormals = true;
  62041. }
  62042. if (this._copy.rotationQuaternion) {
  62043. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62044. }
  62045. else {
  62046. this._yaw = this._copy.rotation.y;
  62047. this._pitch = this._copy.rotation.x;
  62048. this._roll = this._copy.rotation.z;
  62049. this._quaternionRotationYPR();
  62050. }
  62051. this._quaternionToRotationMatrix();
  62052. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62053. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62054. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62055. if (this._copy.translateFromPivot) {
  62056. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62057. }
  62058. else {
  62059. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62060. }
  62061. for (i = 0; i < shape.length; i++) {
  62062. this._vertex.x = shape[i].x;
  62063. this._vertex.y = shape[i].y;
  62064. this._vertex.z = shape[i].z;
  62065. if (options && options.vertexFunction) {
  62066. options.vertexFunction(this._copy, this._vertex, i);
  62067. }
  62068. this._vertex.x *= this._copy.scaling.x;
  62069. this._vertex.y *= this._copy.scaling.y;
  62070. this._vertex.z *= this._copy.scaling.z;
  62071. this._vertex.x -= this._scaledPivot.x;
  62072. this._vertex.y -= this._scaledPivot.y;
  62073. this._vertex.z -= this._scaledPivot.z;
  62074. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62075. this._rotated.addInPlace(this._pivotBackTranslation);
  62076. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62077. if (meshUV) {
  62078. 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);
  62079. u += 2;
  62080. }
  62081. if (this._copy.color) {
  62082. this._color = this._copy.color;
  62083. }
  62084. else if (meshCol && meshCol[c] !== undefined) {
  62085. this._color.r = meshCol[c];
  62086. this._color.g = meshCol[c + 1];
  62087. this._color.b = meshCol[c + 2];
  62088. this._color.a = meshCol[c + 3];
  62089. }
  62090. else {
  62091. this._color.r = 1.0;
  62092. this._color.g = 1.0;
  62093. this._color.b = 1.0;
  62094. this._color.a = 1.0;
  62095. }
  62096. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62097. c += 4;
  62098. if (!this.recomputeNormals && meshNor) {
  62099. this._normal.x = meshNor[n];
  62100. this._normal.y = meshNor[n + 1];
  62101. this._normal.z = meshNor[n + 2];
  62102. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62103. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62104. n += 3;
  62105. }
  62106. }
  62107. for (i = 0; i < meshInd.length; i++) {
  62108. var current_ind = p + meshInd[i];
  62109. indices.push(current_ind);
  62110. if (current_ind > 65535) {
  62111. this._needs32Bits = true;
  62112. }
  62113. }
  62114. if (this._pickable) {
  62115. var nbfaces = meshInd.length / 3;
  62116. for (i = 0; i < nbfaces; i++) {
  62117. this.pickedParticles.push({ idx: idx, faceId: i });
  62118. }
  62119. }
  62120. if (this._depthSort) {
  62121. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62122. }
  62123. return this._copy;
  62124. };
  62125. // returns a shape array from positions array
  62126. SolidParticleSystem.prototype._posToShape = function (positions) {
  62127. var shape = [];
  62128. for (var i = 0; i < positions.length; i += 3) {
  62129. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62130. }
  62131. return shape;
  62132. };
  62133. // returns a shapeUV array from a Vector4 uvs
  62134. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62135. var shapeUV = [];
  62136. if (uvs) {
  62137. for (var i = 0; i < uvs.length; i++)
  62138. shapeUV.push(uvs[i]);
  62139. }
  62140. return shapeUV;
  62141. };
  62142. // adds a new particle object in the particles array
  62143. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62144. if (bInfo === void 0) { bInfo = null; }
  62145. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62146. this.particles.push(sp);
  62147. return sp;
  62148. };
  62149. /**
  62150. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62151. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62152. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62153. * @param nb (positive integer) the number of particles to be created from this model
  62154. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62155. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62156. * @returns the number of shapes in the system
  62157. */
  62158. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62159. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62160. var meshInd = mesh.getIndices();
  62161. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62162. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62163. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62164. var bbInfo;
  62165. if (this._particlesIntersect) {
  62166. bbInfo = mesh.getBoundingInfo();
  62167. }
  62168. var shape = this._posToShape(meshPos);
  62169. var shapeUV = this._uvsToShapeUV(meshUV);
  62170. var posfunc = options ? options.positionFunction : null;
  62171. var vtxfunc = options ? options.vertexFunction : null;
  62172. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62173. // particles
  62174. var sp;
  62175. var currentCopy;
  62176. var idx = this.nbParticles;
  62177. for (var i = 0; i < nb; i++) {
  62178. var currentPos = this._positions.length;
  62179. var currentInd = this._indices.length;
  62180. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62181. if (this._updatable) {
  62182. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62183. sp.position.copyFrom(currentCopy.position);
  62184. sp.rotation.copyFrom(currentCopy.rotation);
  62185. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62186. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62187. }
  62188. if (currentCopy.color && sp.color) {
  62189. sp.color.copyFrom(currentCopy.color);
  62190. }
  62191. sp.scaling.copyFrom(currentCopy.scaling);
  62192. sp.uvs.copyFrom(currentCopy.uvs);
  62193. }
  62194. this._index += shape.length;
  62195. idx++;
  62196. }
  62197. this.nbParticles += nb;
  62198. this._shapeCounter++;
  62199. return this._shapeCounter - 1;
  62200. };
  62201. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62202. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62203. this._resetCopy();
  62204. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62205. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62206. }
  62207. if (this._copy.rotationQuaternion) {
  62208. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62209. }
  62210. else {
  62211. this._yaw = this._copy.rotation.y;
  62212. this._pitch = this._copy.rotation.x;
  62213. this._roll = this._copy.rotation.z;
  62214. this._quaternionRotationYPR();
  62215. }
  62216. this._quaternionToRotationMatrix();
  62217. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62218. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62219. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62220. if (this._copy.translateFromPivot) {
  62221. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62222. }
  62223. else {
  62224. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62225. }
  62226. this._shape = particle._model._shape;
  62227. for (var pt = 0; pt < this._shape.length; pt++) {
  62228. this._vertex.x = this._shape[pt].x;
  62229. this._vertex.y = this._shape[pt].y;
  62230. this._vertex.z = this._shape[pt].z;
  62231. if (particle._model._vertexFunction) {
  62232. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62233. }
  62234. this._vertex.x *= this._copy.scaling.x;
  62235. this._vertex.y *= this._copy.scaling.y;
  62236. this._vertex.z *= this._copy.scaling.z;
  62237. this._vertex.x -= this._scaledPivot.x;
  62238. this._vertex.y -= this._scaledPivot.y;
  62239. this._vertex.z -= this._scaledPivot.z;
  62240. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62241. this._rotated.addInPlace(this._pivotBackTranslation);
  62242. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62243. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62244. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62245. }
  62246. particle.position.x = 0.0;
  62247. particle.position.y = 0.0;
  62248. particle.position.z = 0.0;
  62249. particle.rotation.x = 0.0;
  62250. particle.rotation.y = 0.0;
  62251. particle.rotation.z = 0.0;
  62252. particle.rotationQuaternion = null;
  62253. particle.scaling.x = 1.0;
  62254. particle.scaling.y = 1.0;
  62255. particle.scaling.z = 1.0;
  62256. particle.uvs.x = 0.0;
  62257. particle.uvs.y = 0.0;
  62258. particle.uvs.z = 1.0;
  62259. particle.uvs.w = 1.0;
  62260. particle.pivot.x = 0.0;
  62261. particle.pivot.y = 0.0;
  62262. particle.pivot.z = 0.0;
  62263. particle.translateFromPivot = false;
  62264. particle.parentId = null;
  62265. };
  62266. /**
  62267. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62268. * @returns the SPS.
  62269. */
  62270. SolidParticleSystem.prototype.rebuildMesh = function () {
  62271. for (var p = 0; p < this.particles.length; p++) {
  62272. this._rebuildParticle(this.particles[p]);
  62273. }
  62274. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62275. return this;
  62276. };
  62277. /**
  62278. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62279. * This method calls `updateParticle()` for each particle of the SPS.
  62280. * For an animated SPS, it is usually called within the render loop.
  62281. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62282. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62283. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62284. * @returns the SPS.
  62285. */
  62286. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62287. if (start === void 0) { start = 0; }
  62288. if (end === void 0) { end = this.nbParticles - 1; }
  62289. if (update === void 0) { update = true; }
  62290. if (!this._updatable) {
  62291. return this;
  62292. }
  62293. // custom beforeUpdate
  62294. this.beforeUpdateParticles(start, end, update);
  62295. this._cam_axisX.x = 1.0;
  62296. this._cam_axisX.y = 0.0;
  62297. this._cam_axisX.z = 0.0;
  62298. this._cam_axisY.x = 0.0;
  62299. this._cam_axisY.y = 1.0;
  62300. this._cam_axisY.z = 0.0;
  62301. this._cam_axisZ.x = 0.0;
  62302. this._cam_axisZ.y = 0.0;
  62303. this._cam_axisZ.z = 1.0;
  62304. // cases when the World Matrix is to be computed first
  62305. if (this.billboard || this._depthSort) {
  62306. this.mesh.computeWorldMatrix(true);
  62307. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62308. }
  62309. // if the particles will always face the camera
  62310. if (this.billboard) {
  62311. // compute the camera position and un-rotate it by the current mesh rotation
  62312. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62313. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62314. this._cam_axisZ.normalize();
  62315. // same for camera up vector extracted from the cam view matrix
  62316. var view = this._camera.getViewMatrix(true);
  62317. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62318. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62319. this._cam_axisY.normalize();
  62320. this._cam_axisX.normalize();
  62321. }
  62322. // if depthSort, compute the camera global position in the mesh local system
  62323. if (this._depthSort) {
  62324. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62325. }
  62326. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62327. var idx = 0; // current position index in the global array positions32
  62328. var index = 0; // position start index in the global array positions32 of the current particle
  62329. var colidx = 0; // current color index in the global array colors32
  62330. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62331. var uvidx = 0; // current uv index in the global array uvs32
  62332. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62333. var pt = 0; // current index in the particle model shape
  62334. if (this.mesh.isFacetDataEnabled) {
  62335. this._computeBoundingBox = true;
  62336. }
  62337. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62338. if (this._computeBoundingBox) {
  62339. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62340. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62341. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62342. }
  62343. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62344. if (this.mesh._boundingInfo) {
  62345. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62346. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62347. }
  62348. }
  62349. }
  62350. // particle loop
  62351. index = this.particles[start]._pos;
  62352. var vpos = (index / 3) | 0;
  62353. colorIndex = vpos * 4;
  62354. uvIndex = vpos * 2;
  62355. for (var p = start; p <= end; p++) {
  62356. this._particle = this.particles[p];
  62357. this._shape = this._particle._model._shape;
  62358. this._shapeUV = this._particle._model._shapeUV;
  62359. // call to custom user function to update the particle properties
  62360. this.updateParticle(this._particle);
  62361. // camera-particle distance for depth sorting
  62362. if (this._depthSort && this._depthSortParticles) {
  62363. var dsp = this.depthSortedParticles[p];
  62364. dsp.ind = this._particle._ind;
  62365. dsp.indicesLength = this._particle._model._indicesLength;
  62366. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62367. }
  62368. // skip the computations for inactive or already invisible particles
  62369. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62370. // increment indexes for the next particle
  62371. pt = this._shape.length;
  62372. index += pt * 3;
  62373. colorIndex += pt * 4;
  62374. uvIndex += pt * 2;
  62375. continue;
  62376. }
  62377. if (this._particle.isVisible) {
  62378. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62379. this._particleHasParent = (this._particle.parentId !== null);
  62380. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62381. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62382. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62383. // particle rotation matrix
  62384. if (this.billboard) {
  62385. this._particle.rotation.x = 0.0;
  62386. this._particle.rotation.y = 0.0;
  62387. }
  62388. if (this._computeParticleRotation || this.billboard) {
  62389. if (this._particle.rotationQuaternion) {
  62390. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62391. }
  62392. else {
  62393. this._yaw = this._particle.rotation.y;
  62394. this._pitch = this._particle.rotation.x;
  62395. this._roll = this._particle.rotation.z;
  62396. this._quaternionRotationYPR();
  62397. }
  62398. this._quaternionToRotationMatrix();
  62399. }
  62400. if (this._particleHasParent) {
  62401. this._parent = this.particles[this._particle.parentId];
  62402. 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];
  62403. 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];
  62404. 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];
  62405. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62406. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62407. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62408. if (this._computeParticleRotation || this.billboard) {
  62409. 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];
  62410. 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];
  62411. 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];
  62412. 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];
  62413. 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];
  62414. 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];
  62415. 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];
  62416. 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];
  62417. 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];
  62418. }
  62419. }
  62420. else {
  62421. this._particle._globalPosition.x = this._particle.position.x;
  62422. this._particle._globalPosition.y = this._particle.position.y;
  62423. this._particle._globalPosition.z = this._particle.position.z;
  62424. if (this._computeParticleRotation || this.billboard) {
  62425. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62426. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62427. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62428. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62429. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62430. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62431. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62432. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62433. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62434. }
  62435. }
  62436. if (this._particle.translateFromPivot) {
  62437. this._pivotBackTranslation.x = 0.0;
  62438. this._pivotBackTranslation.y = 0.0;
  62439. this._pivotBackTranslation.z = 0.0;
  62440. }
  62441. else {
  62442. this._pivotBackTranslation.x = this._scaledPivot.x;
  62443. this._pivotBackTranslation.y = this._scaledPivot.y;
  62444. this._pivotBackTranslation.z = this._scaledPivot.z;
  62445. }
  62446. // particle vertex loop
  62447. for (pt = 0; pt < this._shape.length; pt++) {
  62448. idx = index + pt * 3;
  62449. colidx = colorIndex + pt * 4;
  62450. uvidx = uvIndex + pt * 2;
  62451. this._vertex.x = this._shape[pt].x;
  62452. this._vertex.y = this._shape[pt].y;
  62453. this._vertex.z = this._shape[pt].z;
  62454. if (this._computeParticleVertex) {
  62455. this.updateParticleVertex(this._particle, this._vertex, pt);
  62456. }
  62457. // positions
  62458. this._vertex.x *= this._particle.scaling.x;
  62459. this._vertex.y *= this._particle.scaling.y;
  62460. this._vertex.z *= this._particle.scaling.z;
  62461. this._vertex.x -= this._scaledPivot.x;
  62462. this._vertex.y -= this._scaledPivot.y;
  62463. this._vertex.z -= this._scaledPivot.z;
  62464. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62465. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62466. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62467. this._rotated.x += this._pivotBackTranslation.x;
  62468. this._rotated.y += this._pivotBackTranslation.y;
  62469. this._rotated.z += this._pivotBackTranslation.z;
  62470. 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;
  62471. 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;
  62472. 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;
  62473. if (this._computeBoundingBox) {
  62474. if (this._positions32[idx] < this._minimum.x) {
  62475. this._minimum.x = this._positions32[idx];
  62476. }
  62477. if (this._positions32[idx] > this._maximum.x) {
  62478. this._maximum.x = this._positions32[idx];
  62479. }
  62480. if (this._positions32[idx + 1] < this._minimum.y) {
  62481. this._minimum.y = this._positions32[idx + 1];
  62482. }
  62483. if (this._positions32[idx + 1] > this._maximum.y) {
  62484. this._maximum.y = this._positions32[idx + 1];
  62485. }
  62486. if (this._positions32[idx + 2] < this._minimum.z) {
  62487. this._minimum.z = this._positions32[idx + 2];
  62488. }
  62489. if (this._positions32[idx + 2] > this._maximum.z) {
  62490. this._maximum.z = this._positions32[idx + 2];
  62491. }
  62492. }
  62493. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62494. if (!this._computeParticleVertex) {
  62495. this._normal.x = this._fixedNormal32[idx];
  62496. this._normal.y = this._fixedNormal32[idx + 1];
  62497. this._normal.z = this._fixedNormal32[idx + 2];
  62498. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62499. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62500. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62501. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62502. 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;
  62503. 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;
  62504. }
  62505. if (this._computeParticleColor && this._particle.color) {
  62506. this._colors32[colidx] = this._particle.color.r;
  62507. this._colors32[colidx + 1] = this._particle.color.g;
  62508. this._colors32[colidx + 2] = this._particle.color.b;
  62509. this._colors32[colidx + 3] = this._particle.color.a;
  62510. }
  62511. if (this._computeParticleTexture) {
  62512. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62513. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62514. }
  62515. }
  62516. }
  62517. // particle just set invisible : scaled to zero and positioned at the origin
  62518. else {
  62519. this._particle._stillInvisible = true; // mark the particle as invisible
  62520. for (pt = 0; pt < this._shape.length; pt++) {
  62521. idx = index + pt * 3;
  62522. colidx = colorIndex + pt * 4;
  62523. uvidx = uvIndex + pt * 2;
  62524. this._positions32[idx] = 0.0;
  62525. this._positions32[idx + 1] = 0.0;
  62526. this._positions32[idx + 2] = 0.0;
  62527. this._normals32[idx] = 0.0;
  62528. this._normals32[idx + 1] = 0.0;
  62529. this._normals32[idx + 2] = 0.0;
  62530. if (this._computeParticleColor && this._particle.color) {
  62531. this._colors32[colidx] = this._particle.color.r;
  62532. this._colors32[colidx + 1] = this._particle.color.g;
  62533. this._colors32[colidx + 2] = this._particle.color.b;
  62534. this._colors32[colidx + 3] = this._particle.color.a;
  62535. }
  62536. if (this._computeParticleTexture) {
  62537. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62538. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62539. }
  62540. }
  62541. }
  62542. // if the particle intersections must be computed : update the bbInfo
  62543. if (this._particlesIntersect) {
  62544. var bInfo = this._particle._boundingInfo;
  62545. var bBox = bInfo.boundingBox;
  62546. var bSphere = bInfo.boundingSphere;
  62547. if (!this._bSphereOnly) {
  62548. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62549. for (var b = 0; b < bBox.vectors.length; b++) {
  62550. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62551. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62552. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62553. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62554. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62555. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62556. 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;
  62557. 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;
  62558. 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;
  62559. }
  62560. bBox._update(this.mesh._worldMatrix);
  62561. }
  62562. // place and scale the particle bouding sphere in the SPS local system, then update it
  62563. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62564. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62565. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62566. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62567. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62568. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62569. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62570. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62571. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62572. 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));
  62573. bSphere._update(this.mesh._worldMatrix);
  62574. }
  62575. // increment indexes for the next particle
  62576. index = idx + 3;
  62577. colorIndex = colidx + 4;
  62578. uvIndex = uvidx + 2;
  62579. }
  62580. // if the VBO must be updated
  62581. if (update) {
  62582. if (this._computeParticleColor) {
  62583. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62584. }
  62585. if (this._computeParticleTexture) {
  62586. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62587. }
  62588. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62589. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62590. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62591. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62592. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62593. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62594. for (var i = 0; i < this._normals32.length; i++) {
  62595. this._fixedNormal32[i] = this._normals32[i];
  62596. }
  62597. }
  62598. if (!this.mesh.areNormalsFrozen) {
  62599. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62600. }
  62601. }
  62602. if (this._depthSort && this._depthSortParticles) {
  62603. this.depthSortedParticles.sort(this._depthSortFunction);
  62604. var dspl = this.depthSortedParticles.length;
  62605. var sorted = 0;
  62606. var lind = 0;
  62607. var sind = 0;
  62608. var sid = 0;
  62609. for (sorted = 0; sorted < dspl; sorted++) {
  62610. lind = this.depthSortedParticles[sorted].indicesLength;
  62611. sind = this.depthSortedParticles[sorted].ind;
  62612. for (var i = 0; i < lind; i++) {
  62613. this._indices32[sid] = this._indices[sind + i];
  62614. sid++;
  62615. }
  62616. }
  62617. this.mesh.updateIndices(this._indices32);
  62618. }
  62619. }
  62620. if (this._computeBoundingBox) {
  62621. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62622. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62623. }
  62624. this.afterUpdateParticles(start, end, update);
  62625. return this;
  62626. };
  62627. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62628. this._halfroll = this._roll * 0.5;
  62629. this._halfpitch = this._pitch * 0.5;
  62630. this._halfyaw = this._yaw * 0.5;
  62631. this._sinRoll = Math.sin(this._halfroll);
  62632. this._cosRoll = Math.cos(this._halfroll);
  62633. this._sinPitch = Math.sin(this._halfpitch);
  62634. this._cosPitch = Math.cos(this._halfpitch);
  62635. this._sinYaw = Math.sin(this._halfyaw);
  62636. this._cosYaw = Math.cos(this._halfyaw);
  62637. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62638. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62639. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62640. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62641. };
  62642. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62643. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62644. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62645. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62646. this._rotMatrix.m[3] = 0;
  62647. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62648. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62649. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62650. this._rotMatrix.m[7] = 0;
  62651. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62652. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62653. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62654. this._rotMatrix.m[11] = 0;
  62655. this._rotMatrix.m[12] = 0;
  62656. this._rotMatrix.m[13] = 0;
  62657. this._rotMatrix.m[14] = 0;
  62658. this._rotMatrix.m[15] = 1.0;
  62659. };
  62660. /**
  62661. * Disposes the SPS.
  62662. */
  62663. SolidParticleSystem.prototype.dispose = function () {
  62664. this.mesh.dispose();
  62665. this.vars = null;
  62666. // drop references to internal big arrays for the GC
  62667. this._positions = null;
  62668. this._indices = null;
  62669. this._normals = null;
  62670. this._uvs = null;
  62671. this._colors = null;
  62672. this._indices32 = null;
  62673. this._positions32 = null;
  62674. this._normals32 = null;
  62675. this._fixedNormal32 = null;
  62676. this._uvs32 = null;
  62677. this._colors32 = null;
  62678. this.pickedParticles = null;
  62679. };
  62680. /**
  62681. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62682. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62683. * @returns the SPS.
  62684. */
  62685. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62686. if (!this._isVisibilityBoxLocked) {
  62687. this.mesh.refreshBoundingInfo();
  62688. }
  62689. return this;
  62690. };
  62691. /**
  62692. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62693. * @param size the size (float) of the visibility box
  62694. * note : this doesn't lock the SPS mesh bounding box.
  62695. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62696. */
  62697. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62698. var vis = size / 2;
  62699. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62700. };
  62701. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62702. /**
  62703. * Gets whether the SPS as always visible or not
  62704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62705. */
  62706. get: function () {
  62707. return this._alwaysVisible;
  62708. },
  62709. /**
  62710. * Sets the SPS as always visible or not
  62711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62712. */
  62713. set: function (val) {
  62714. this._alwaysVisible = val;
  62715. this.mesh.alwaysSelectAsActiveMesh = val;
  62716. },
  62717. enumerable: true,
  62718. configurable: true
  62719. });
  62720. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62721. /**
  62722. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62724. */
  62725. get: function () {
  62726. return this._isVisibilityBoxLocked;
  62727. },
  62728. /**
  62729. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62730. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62731. */
  62732. set: function (val) {
  62733. this._isVisibilityBoxLocked = val;
  62734. var boundingInfo = this.mesh.getBoundingInfo();
  62735. boundingInfo.isLocked = val;
  62736. },
  62737. enumerable: true,
  62738. configurable: true
  62739. });
  62740. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62741. /**
  62742. * Gets if `setParticles()` computes the particle rotations or not.
  62743. * Default value : true. The SPS is faster when it's set to false.
  62744. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62745. */
  62746. get: function () {
  62747. return this._computeParticleRotation;
  62748. },
  62749. /**
  62750. * Tells to `setParticles()` to compute the particle rotations or not.
  62751. * Default value : true. The SPS is faster when it's set to false.
  62752. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62753. */
  62754. set: function (val) {
  62755. this._computeParticleRotation = val;
  62756. },
  62757. enumerable: true,
  62758. configurable: true
  62759. });
  62760. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62761. /**
  62762. * Gets if `setParticles()` computes the particle colors or not.
  62763. * Default value : true. The SPS is faster when it's set to false.
  62764. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62765. */
  62766. get: function () {
  62767. return this._computeParticleColor;
  62768. },
  62769. /**
  62770. * Tells to `setParticles()` to compute the particle colors or not.
  62771. * Default value : true. The SPS is faster when it's set to false.
  62772. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62773. */
  62774. set: function (val) {
  62775. this._computeParticleColor = val;
  62776. },
  62777. enumerable: true,
  62778. configurable: true
  62779. });
  62780. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  62781. /**
  62782. * Gets if `setParticles()` computes the particle textures or not.
  62783. * Default value : true. The SPS is faster when it's set to false.
  62784. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  62785. */
  62786. get: function () {
  62787. return this._computeParticleTexture;
  62788. },
  62789. set: function (val) {
  62790. this._computeParticleTexture = val;
  62791. },
  62792. enumerable: true,
  62793. configurable: true
  62794. });
  62795. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  62796. /**
  62797. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  62798. * Default value : false. The SPS is faster when it's set to false.
  62799. * Note : the particle custom vertex positions aren't stored values.
  62800. */
  62801. get: function () {
  62802. return this._computeParticleVertex;
  62803. },
  62804. /**
  62805. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  62806. * Default value : false. The SPS is faster when it's set to false.
  62807. * Note : the particle custom vertex positions aren't stored values.
  62808. */
  62809. set: function (val) {
  62810. this._computeParticleVertex = val;
  62811. },
  62812. enumerable: true,
  62813. configurable: true
  62814. });
  62815. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  62816. /**
  62817. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  62818. */
  62819. get: function () {
  62820. return this._computeBoundingBox;
  62821. },
  62822. /**
  62823. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  62824. */
  62825. set: function (val) {
  62826. this._computeBoundingBox = val;
  62827. },
  62828. enumerable: true,
  62829. configurable: true
  62830. });
  62831. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62832. /**
  62833. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62834. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62835. * Default : `true`
  62836. */
  62837. get: function () {
  62838. return this._depthSortParticles;
  62839. },
  62840. /**
  62841. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62842. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62843. * Default : `true`
  62844. */
  62845. set: function (val) {
  62846. this._depthSortParticles = val;
  62847. },
  62848. enumerable: true,
  62849. configurable: true
  62850. });
  62851. // =======================================================================
  62852. // Particle behavior logic
  62853. // these following methods may be overwritten by the user to fit his needs
  62854. /**
  62855. * This function does nothing. It may be overwritten to set all the particle first values.
  62856. * The SPS doesn't call this function, you may have to call it by your own.
  62857. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62858. */
  62859. SolidParticleSystem.prototype.initParticles = function () {
  62860. };
  62861. /**
  62862. * This function does nothing. It may be overwritten to recycle a particle.
  62863. * The SPS doesn't call this function, you may have to call it by your own.
  62864. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62865. * @param particle The particle to recycle
  62866. * @returns the recycled particle
  62867. */
  62868. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62869. return particle;
  62870. };
  62871. /**
  62872. * Updates a particle : this function should be overwritten by the user.
  62873. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62874. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62875. * @example : just set a particle position or velocity and recycle conditions
  62876. * @param particle The particle to update
  62877. * @returns the updated particle
  62878. */
  62879. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62880. return particle;
  62881. };
  62882. /**
  62883. * Updates a vertex of a particle : it can be overwritten by the user.
  62884. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62885. * @param particle the current particle
  62886. * @param vertex the current index of the current particle
  62887. * @param pt the index of the current vertex in the particle shape
  62888. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62889. * @example : just set a vertex particle position
  62890. * @returns the updated vertex
  62891. */
  62892. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62893. return vertex;
  62894. };
  62895. /**
  62896. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62897. * This does nothing and may be overwritten by the user.
  62898. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62899. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62900. * @param update the boolean update value actually passed to setParticles()
  62901. */
  62902. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62903. };
  62904. /**
  62905. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62906. * This will be passed three parameters.
  62907. * This does nothing and may be overwritten by the user.
  62908. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62909. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62910. * @param update the boolean update value actually passed to setParticles()
  62911. */
  62912. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62913. };
  62914. return SolidParticleSystem;
  62915. }());
  62916. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62917. })(BABYLON || (BABYLON = {}));
  62918. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62919. var BABYLON;
  62920. (function (BABYLON) {
  62921. /**
  62922. * Class containing static functions to help procedurally build meshes
  62923. */
  62924. var MeshBuilder = /** @class */ (function () {
  62925. function MeshBuilder() {
  62926. }
  62927. MeshBuilder.updateSideOrientation = function (orientation) {
  62928. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62929. return BABYLON.Mesh.DOUBLESIDE;
  62930. }
  62931. if (orientation === undefined || orientation === null) {
  62932. return BABYLON.Mesh.FRONTSIDE;
  62933. }
  62934. return orientation;
  62935. };
  62936. /**
  62937. * Creates a box mesh
  62938. * * The parameter `size` sets the size (float) of each box side (default 1)
  62939. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62940. * * 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)
  62941. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62942. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62943. * * 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
  62944. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62945. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62946. * @param name defines the name of the mesh
  62947. * @param options defines the options used to create the mesh
  62948. * @param scene defines the hosting scene
  62949. * @returns the box mesh
  62950. */
  62951. MeshBuilder.CreateBox = function (name, options, scene) {
  62952. if (scene === void 0) { scene = null; }
  62953. var box = new BABYLON.Mesh(name, scene);
  62954. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62955. box._originalBuilderSideOrientation = options.sideOrientation;
  62956. var vertexData = BABYLON.VertexData.CreateBox(options);
  62957. vertexData.applyToMesh(box, options.updatable);
  62958. return box;
  62959. };
  62960. /**
  62961. * Creates a sphere mesh
  62962. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62963. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  62964. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62965. * * 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
  62966. * * 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)
  62967. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62968. * * 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
  62969. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62970. * @param name defines the name of the mesh
  62971. * @param options defines the options used to create the mesh
  62972. * @param scene defines the hosting scene
  62973. * @returns the sphere mesh
  62974. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62975. */
  62976. MeshBuilder.CreateSphere = function (name, options, scene) {
  62977. var sphere = new BABYLON.Mesh(name, scene);
  62978. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62979. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62980. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62981. vertexData.applyToMesh(sphere, options.updatable);
  62982. return sphere;
  62983. };
  62984. /**
  62985. * Creates a plane polygonal mesh. By default, this is a disc
  62986. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62987. * * 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
  62988. * * 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
  62989. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62990. * * 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
  62991. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62992. * @param name defines the name of the mesh
  62993. * @param options defines the options used to create the mesh
  62994. * @param scene defines the hosting scene
  62995. * @returns the plane polygonal mesh
  62996. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62997. */
  62998. MeshBuilder.CreateDisc = function (name, options, scene) {
  62999. if (scene === void 0) { scene = null; }
  63000. var disc = new BABYLON.Mesh(name, scene);
  63001. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63002. disc._originalBuilderSideOrientation = options.sideOrientation;
  63003. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63004. vertexData.applyToMesh(disc, options.updatable);
  63005. return disc;
  63006. };
  63007. /**
  63008. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63009. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63010. * * 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`)
  63011. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63012. * * 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
  63013. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63014. * * 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
  63015. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63016. * @param name defines the name of the mesh
  63017. * @param options defines the options used to create the mesh
  63018. * @param scene defines the hosting scene
  63019. * @returns the icosahedron mesh
  63020. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63021. */
  63022. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63023. var sphere = new BABYLON.Mesh(name, scene);
  63024. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63025. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63026. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63027. vertexData.applyToMesh(sphere, options.updatable);
  63028. return sphere;
  63029. };
  63030. ;
  63031. /**
  63032. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63033. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63034. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63035. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63036. * * 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
  63037. * * 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
  63038. * * 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
  63039. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63040. * * 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
  63041. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63042. * * 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
  63043. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63044. * * 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
  63045. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63046. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63047. * @param name defines the name of the mesh
  63048. * @param options defines the options used to create the mesh
  63049. * @param scene defines the hosting scene
  63050. * @returns the ribbon mesh
  63051. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63052. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63053. */
  63054. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63055. if (scene === void 0) { scene = null; }
  63056. var pathArray = options.pathArray;
  63057. var closeArray = options.closeArray;
  63058. var closePath = options.closePath;
  63059. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63060. var instance = options.instance;
  63061. var updatable = options.updatable;
  63062. if (instance) { // existing ribbon instance update
  63063. // positionFunction : ribbon case
  63064. // only pathArray and sideOrientation parameters are taken into account for positions update
  63065. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63066. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63067. var positionFunction = function (positions) {
  63068. var minlg = pathArray[0].length;
  63069. var i = 0;
  63070. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63071. for (var si = 1; si <= ns; si++) {
  63072. for (var p = 0; p < pathArray.length; p++) {
  63073. var path = pathArray[p];
  63074. var l = path.length;
  63075. minlg = (minlg < l) ? minlg : l;
  63076. var j = 0;
  63077. while (j < minlg) {
  63078. positions[i] = path[j].x;
  63079. positions[i + 1] = path[j].y;
  63080. positions[i + 2] = path[j].z;
  63081. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63082. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63083. }
  63084. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63085. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63086. }
  63087. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63088. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63089. }
  63090. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63091. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63092. }
  63093. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63094. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63095. }
  63096. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63097. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63098. }
  63099. j++;
  63100. i += 3;
  63101. }
  63102. if (instance._closePath) {
  63103. positions[i] = path[0].x;
  63104. positions[i + 1] = path[0].y;
  63105. positions[i + 2] = path[0].z;
  63106. i += 3;
  63107. }
  63108. }
  63109. }
  63110. };
  63111. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63112. positionFunction(positions);
  63113. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63114. instance._boundingInfo.update(instance._worldMatrix);
  63115. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63116. if (options.colors) {
  63117. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63118. for (var c = 0; c < options.colors.length; c++) {
  63119. colors[c * 4] = options.colors[c].r;
  63120. colors[c * 4 + 1] = options.colors[c].g;
  63121. colors[c * 4 + 2] = options.colors[c].b;
  63122. colors[c * 4 + 3] = options.colors[c].a;
  63123. }
  63124. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63125. }
  63126. if (options.uvs) {
  63127. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63128. for (var i = 0; i < options.uvs.length; i++) {
  63129. uvs[i * 2] = options.uvs[i].x;
  63130. uvs[i * 2 + 1] = options.uvs[i].y;
  63131. }
  63132. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63133. }
  63134. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63135. var indices = instance.getIndices();
  63136. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63137. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63138. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63139. if (instance._closePath) {
  63140. var indexFirst = 0;
  63141. var indexLast = 0;
  63142. for (var p = 0; p < pathArray.length; p++) {
  63143. indexFirst = instance._idx[p] * 3;
  63144. if (p + 1 < pathArray.length) {
  63145. indexLast = (instance._idx[p + 1] - 1) * 3;
  63146. }
  63147. else {
  63148. indexLast = normals.length - 3;
  63149. }
  63150. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63151. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63152. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63153. normals[indexLast] = normals[indexFirst];
  63154. normals[indexLast + 1] = normals[indexFirst + 1];
  63155. normals[indexLast + 2] = normals[indexFirst + 2];
  63156. }
  63157. }
  63158. if (!(instance.areNormalsFrozen)) {
  63159. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63160. }
  63161. }
  63162. return instance;
  63163. }
  63164. else { // new ribbon creation
  63165. var ribbon = new BABYLON.Mesh(name, scene);
  63166. ribbon._originalBuilderSideOrientation = sideOrientation;
  63167. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63168. if (closePath) {
  63169. ribbon._idx = vertexData._idx;
  63170. }
  63171. ribbon._closePath = closePath;
  63172. ribbon._closeArray = closeArray;
  63173. vertexData.applyToMesh(ribbon, updatable);
  63174. return ribbon;
  63175. }
  63176. };
  63177. /**
  63178. * Creates a cylinder or a cone mesh
  63179. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63180. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63181. * * 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.
  63182. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63183. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63184. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63185. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63186. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63187. * * 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).
  63188. * * 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
  63189. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63190. * * 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
  63191. * * 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.
  63192. * * If `enclose` is false, a ring surface is one element.
  63193. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63194. * * 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
  63195. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63196. * * 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
  63197. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63198. * @param name defines the name of the mesh
  63199. * @param options defines the options used to create the mesh
  63200. * @param scene defines the hosting scene
  63201. * @returns the cylinder mesh
  63202. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63203. */
  63204. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63205. var cylinder = new BABYLON.Mesh(name, scene);
  63206. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63207. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63208. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63209. vertexData.applyToMesh(cylinder, options.updatable);
  63210. return cylinder;
  63211. };
  63212. /**
  63213. * Creates a torus mesh
  63214. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63215. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63216. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63217. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63218. * * 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
  63219. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63220. * @param name defines the name of the mesh
  63221. * @param options defines the options used to create the mesh
  63222. * @param scene defines the hosting scene
  63223. * @returns the torus mesh
  63224. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63225. */
  63226. MeshBuilder.CreateTorus = function (name, options, scene) {
  63227. var torus = new BABYLON.Mesh(name, scene);
  63228. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63229. torus._originalBuilderSideOrientation = options.sideOrientation;
  63230. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63231. vertexData.applyToMesh(torus, options.updatable);
  63232. return torus;
  63233. };
  63234. /**
  63235. * Creates a torus knot mesh
  63236. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63237. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63238. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63239. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63240. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63241. * * 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
  63242. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63243. * @param name defines the name of the mesh
  63244. * @param options defines the options used to create the mesh
  63245. * @param scene defines the hosting scene
  63246. * @returns the torus knot mesh
  63247. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63248. */
  63249. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63250. var torusKnot = new BABYLON.Mesh(name, scene);
  63251. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63252. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63253. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63254. vertexData.applyToMesh(torusKnot, options.updatable);
  63255. return torusKnot;
  63256. };
  63257. /**
  63258. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63259. * * 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
  63260. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63261. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63262. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63263. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63264. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63265. * * 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
  63266. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63267. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63268. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63269. * @param name defines the name of the new line system
  63270. * @param options defines the options used to create the line system
  63271. * @param scene defines the hosting scene
  63272. * @returns a new line system mesh
  63273. */
  63274. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63275. var instance = options.instance;
  63276. var lines = options.lines;
  63277. var colors = options.colors;
  63278. if (instance) { // lines update
  63279. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63280. var vertexColor;
  63281. var lineColors;
  63282. if (colors) {
  63283. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63284. }
  63285. var i = 0;
  63286. var c = 0;
  63287. for (var l = 0; l < lines.length; l++) {
  63288. var points = lines[l];
  63289. for (var p = 0; p < points.length; p++) {
  63290. positions[i] = points[p].x;
  63291. positions[i + 1] = points[p].y;
  63292. positions[i + 2] = points[p].z;
  63293. if (colors && vertexColor) {
  63294. lineColors = colors[l];
  63295. vertexColor[c] = lineColors[p].r;
  63296. vertexColor[c + 1] = lineColors[p].g;
  63297. vertexColor[c + 2] = lineColors[p].b;
  63298. vertexColor[c + 3] = lineColors[p].a;
  63299. c += 4;
  63300. }
  63301. i += 3;
  63302. }
  63303. }
  63304. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63305. if (colors && vertexColor) {
  63306. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63307. }
  63308. return instance;
  63309. }
  63310. // line system creation
  63311. var useVertexColor = (colors) ? true : false;
  63312. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63313. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63314. vertexData.applyToMesh(lineSystem, options.updatable);
  63315. return lineSystem;
  63316. };
  63317. /**
  63318. * Creates a line mesh
  63319. * 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
  63320. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63321. * * The parameter `points` is an array successive Vector3
  63322. * * 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
  63323. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63324. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63325. * * When updating an instance, remember that only point positions can change, not the number of points
  63326. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63327. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63328. * @param name defines the name of the new line system
  63329. * @param options defines the options used to create the line system
  63330. * @param scene defines the hosting scene
  63331. * @returns a new line mesh
  63332. */
  63333. MeshBuilder.CreateLines = function (name, options, scene) {
  63334. if (scene === void 0) { scene = null; }
  63335. var colors = (options.colors) ? [options.colors] : null;
  63336. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63337. return lines;
  63338. };
  63339. /**
  63340. * Creates a dashed line mesh
  63341. * * 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
  63342. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63343. * * The parameter `points` is an array successive Vector3
  63344. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63345. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63346. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63347. * * 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
  63348. * * When updating an instance, remember that only point positions can change, not the number of points
  63349. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63350. * @param name defines the name of the mesh
  63351. * @param options defines the options used to create the mesh
  63352. * @param scene defines the hosting scene
  63353. * @returns the dashed line mesh
  63354. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63355. */
  63356. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63357. if (scene === void 0) { scene = null; }
  63358. var points = options.points;
  63359. var instance = options.instance;
  63360. var gapSize = options.gapSize || 1;
  63361. var dashSize = options.dashSize || 3;
  63362. if (instance) { // dashed lines update
  63363. var positionFunction = function (positions) {
  63364. var curvect = BABYLON.Vector3.Zero();
  63365. var nbSeg = positions.length / 6;
  63366. var lg = 0;
  63367. var nb = 0;
  63368. var shft = 0;
  63369. var dashshft = 0;
  63370. var curshft = 0;
  63371. var p = 0;
  63372. var i = 0;
  63373. var j = 0;
  63374. for (i = 0; i < points.length - 1; i++) {
  63375. points[i + 1].subtractToRef(points[i], curvect);
  63376. lg += curvect.length();
  63377. }
  63378. shft = lg / nbSeg;
  63379. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63380. for (i = 0; i < points.length - 1; i++) {
  63381. points[i + 1].subtractToRef(points[i], curvect);
  63382. nb = Math.floor(curvect.length() / shft);
  63383. curvect.normalize();
  63384. j = 0;
  63385. while (j < nb && p < positions.length) {
  63386. curshft = shft * j;
  63387. positions[p] = points[i].x + curshft * curvect.x;
  63388. positions[p + 1] = points[i].y + curshft * curvect.y;
  63389. positions[p + 2] = points[i].z + curshft * curvect.z;
  63390. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63391. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63392. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63393. p += 6;
  63394. j++;
  63395. }
  63396. }
  63397. while (p < positions.length) {
  63398. positions[p] = points[i].x;
  63399. positions[p + 1] = points[i].y;
  63400. positions[p + 2] = points[i].z;
  63401. p += 3;
  63402. }
  63403. };
  63404. instance.updateMeshPositions(positionFunction, false);
  63405. return instance;
  63406. }
  63407. // dashed lines creation
  63408. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63409. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63410. vertexData.applyToMesh(dashedLines, options.updatable);
  63411. dashedLines.dashSize = dashSize;
  63412. dashedLines.gapSize = gapSize;
  63413. return dashedLines;
  63414. };
  63415. /**
  63416. * 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.
  63417. * * 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.
  63418. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63419. * * 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.
  63420. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63421. * * 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
  63422. * * 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
  63423. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63424. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63425. * * 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
  63426. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63427. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63428. * @param name defines the name of the mesh
  63429. * @param options defines the options used to create the mesh
  63430. * @param scene defines the hosting scene
  63431. * @returns the extruded shape mesh
  63432. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63433. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63434. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63435. */
  63436. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63437. if (scene === void 0) { scene = null; }
  63438. var path = options.path;
  63439. var shape = options.shape;
  63440. var scale = options.scale || 1;
  63441. var rotation = options.rotation || 0;
  63442. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63443. var updatable = options.updatable;
  63444. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63445. var instance = options.instance || null;
  63446. var invertUV = options.invertUV || false;
  63447. 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);
  63448. };
  63449. /**
  63450. * Creates an custom extruded shape mesh.
  63451. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63452. * * 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.
  63453. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63454. * * 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
  63455. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63456. * * 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
  63457. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63458. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63459. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63460. * * 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
  63461. * * 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
  63462. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63463. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63464. * * 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
  63465. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63466. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63467. * @param name defines the name of the mesh
  63468. * @param options defines the options used to create the mesh
  63469. * @param scene defines the hosting scene
  63470. * @returns the custom extruded shape mesh
  63471. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63472. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63473. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63474. */
  63475. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63476. var path = options.path;
  63477. var shape = options.shape;
  63478. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63479. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63480. var ribbonCloseArray = options.ribbonCloseArray || false;
  63481. var ribbonClosePath = options.ribbonClosePath || false;
  63482. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63483. var updatable = options.updatable;
  63484. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63485. var instance = options.instance;
  63486. var invertUV = options.invertUV || false;
  63487. 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);
  63488. };
  63489. /**
  63490. * Creates lathe mesh.
  63491. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63492. * * 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
  63493. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63494. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63495. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63496. * * 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
  63497. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63498. * * 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
  63499. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63500. * * 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
  63501. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63502. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63503. * @param name defines the name of the mesh
  63504. * @param options defines the options used to create the mesh
  63505. * @param scene defines the hosting scene
  63506. * @returns the lathe mesh
  63507. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63508. */
  63509. MeshBuilder.CreateLathe = function (name, options, scene) {
  63510. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63511. var closed = (options.closed === undefined) ? true : options.closed;
  63512. var shape = options.shape;
  63513. var radius = options.radius || 1;
  63514. var tessellation = options.tessellation || 64;
  63515. var clip = options.clip || 0;
  63516. var updatable = options.updatable;
  63517. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63518. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63519. var pi2 = Math.PI * 2;
  63520. var paths = new Array();
  63521. var invertUV = options.invertUV || false;
  63522. var i = 0;
  63523. var p = 0;
  63524. var step = pi2 / tessellation * arc;
  63525. var rotated;
  63526. var path = new Array();
  63527. for (i = 0; i <= tessellation - clip; i++) {
  63528. var path = [];
  63529. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63530. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63531. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63532. }
  63533. for (p = 0; p < shape.length; p++) {
  63534. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63535. path.push(rotated);
  63536. }
  63537. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63538. 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));
  63539. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63540. }
  63541. paths.push(path);
  63542. }
  63543. // lathe ribbon
  63544. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63545. return lathe;
  63546. };
  63547. /**
  63548. * Creates a plane mesh
  63549. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63550. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63551. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63552. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63553. * * 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
  63554. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63555. * @param name defines the name of the mesh
  63556. * @param options defines the options used to create the mesh
  63557. * @param scene defines the hosting scene
  63558. * @returns the plane mesh
  63559. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63560. */
  63561. MeshBuilder.CreatePlane = function (name, options, scene) {
  63562. var plane = new BABYLON.Mesh(name, scene);
  63563. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63564. plane._originalBuilderSideOrientation = options.sideOrientation;
  63565. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63566. vertexData.applyToMesh(plane, options.updatable);
  63567. if (options.sourcePlane) {
  63568. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63569. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63570. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63571. plane.rotate(vectorProduct, product);
  63572. }
  63573. return plane;
  63574. };
  63575. /**
  63576. * Creates a ground mesh
  63577. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63578. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63579. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63580. * @param name defines the name of the mesh
  63581. * @param options defines the options used to create the mesh
  63582. * @param scene defines the hosting scene
  63583. * @returns the ground mesh
  63584. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63585. */
  63586. MeshBuilder.CreateGround = function (name, options, scene) {
  63587. var ground = new BABYLON.GroundMesh(name, scene);
  63588. ground._setReady(false);
  63589. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63590. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63591. ground._width = options.width || 1;
  63592. ground._height = options.height || 1;
  63593. ground._maxX = ground._width / 2;
  63594. ground._maxZ = ground._height / 2;
  63595. ground._minX = -ground._maxX;
  63596. ground._minZ = -ground._maxZ;
  63597. var vertexData = BABYLON.VertexData.CreateGround(options);
  63598. vertexData.applyToMesh(ground, options.updatable);
  63599. ground._setReady(true);
  63600. return ground;
  63601. };
  63602. /**
  63603. * Creates a tiled ground mesh
  63604. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63605. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63606. * * 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
  63607. * * 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
  63608. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63609. * @param name defines the name of the mesh
  63610. * @param options defines the options used to create the mesh
  63611. * @param scene defines the hosting scene
  63612. * @returns the tiled ground mesh
  63613. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63614. */
  63615. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63616. var tiledGround = new BABYLON.Mesh(name, scene);
  63617. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63618. vertexData.applyToMesh(tiledGround, options.updatable);
  63619. return tiledGround;
  63620. };
  63621. /**
  63622. * Creates a ground mesh from a height map
  63623. * * The parameter `url` sets the URL of the height map image resource.
  63624. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63625. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63626. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63627. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63628. * * 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.
  63629. * * 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).
  63630. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63631. * @param name defines the name of the mesh
  63632. * @param url defines the url to the height map
  63633. * @param options defines the options used to create the mesh
  63634. * @param scene defines the hosting scene
  63635. * @returns the ground mesh
  63636. * @see http://doc.babylonjs.com/babylon101/height_map
  63637. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63638. */
  63639. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63640. var width = options.width || 10.0;
  63641. var height = options.height || 10.0;
  63642. var subdivisions = options.subdivisions || 1 | 0;
  63643. var minHeight = options.minHeight || 0.0;
  63644. var maxHeight = options.maxHeight || 1.0;
  63645. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63646. var updatable = options.updatable;
  63647. var onReady = options.onReady;
  63648. var ground = new BABYLON.GroundMesh(name, scene);
  63649. ground._subdivisionsX = subdivisions;
  63650. ground._subdivisionsY = subdivisions;
  63651. ground._width = width;
  63652. ground._height = height;
  63653. ground._maxX = ground._width / 2.0;
  63654. ground._maxZ = ground._height / 2.0;
  63655. ground._minX = -ground._maxX;
  63656. ground._minZ = -ground._maxZ;
  63657. ground._setReady(false);
  63658. var onload = function (img) {
  63659. // Getting height map data
  63660. var canvas = document.createElement("canvas");
  63661. var context = canvas.getContext("2d");
  63662. if (!context) {
  63663. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63664. }
  63665. if (scene.isDisposed) {
  63666. return;
  63667. }
  63668. var bufferWidth = img.width;
  63669. var bufferHeight = img.height;
  63670. canvas.width = bufferWidth;
  63671. canvas.height = bufferHeight;
  63672. context.drawImage(img, 0, 0);
  63673. // Create VertexData from map data
  63674. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63675. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63676. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63677. width: width, height: height,
  63678. subdivisions: subdivisions,
  63679. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63680. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63681. });
  63682. vertexData.applyToMesh(ground, updatable);
  63683. //execute ready callback, if set
  63684. if (onReady) {
  63685. onReady(ground);
  63686. }
  63687. ground._setReady(true);
  63688. };
  63689. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63690. return ground;
  63691. };
  63692. /**
  63693. * Creates a polygon mesh
  63694. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63695. * * 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
  63696. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63697. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63698. * * 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)
  63699. * * Remember you can only change the shape positions, not their number when updating a polygon
  63700. * @param name defines the name of the mesh
  63701. * @param options defines the options used to create the mesh
  63702. * @param scene defines the hosting scene
  63703. * @returns the polygon mesh
  63704. */
  63705. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63706. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63707. var shape = options.shape;
  63708. var holes = options.holes || [];
  63709. var depth = options.depth || 0;
  63710. var contours = [];
  63711. var hole = [];
  63712. for (var i = 0; i < shape.length; i++) {
  63713. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63714. }
  63715. var epsilon = 0.00000001;
  63716. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63717. contours.pop();
  63718. }
  63719. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63720. for (var hNb = 0; hNb < holes.length; hNb++) {
  63721. hole = [];
  63722. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63723. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63724. }
  63725. polygonTriangulation.addHole(hole);
  63726. }
  63727. var polygon = polygonTriangulation.build(options.updatable, depth);
  63728. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63729. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63730. vertexData.applyToMesh(polygon, options.updatable);
  63731. return polygon;
  63732. };
  63733. ;
  63734. /**
  63735. * Creates an extruded polygon mesh, with depth in the Y direction.
  63736. * * 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)
  63737. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63738. * @param name defines the name of the mesh
  63739. * @param options defines the options used to create the mesh
  63740. * @param scene defines the hosting scene
  63741. * @returns the polygon mesh
  63742. */
  63743. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63744. return MeshBuilder.CreatePolygon(name, options, scene);
  63745. };
  63746. ;
  63747. /**
  63748. * Creates a tube mesh.
  63749. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63750. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63751. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63752. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63753. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63754. * * 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)
  63755. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63756. * * 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
  63757. * * 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
  63758. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63759. * * 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
  63760. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63761. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63762. * @param name defines the name of the mesh
  63763. * @param options defines the options used to create the mesh
  63764. * @param scene defines the hosting scene
  63765. * @returns the tube mesh
  63766. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63767. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63768. */
  63769. MeshBuilder.CreateTube = function (name, options, scene) {
  63770. var path = options.path;
  63771. var instance = options.instance;
  63772. var radius = 1.0;
  63773. if (instance) {
  63774. radius = instance.radius;
  63775. }
  63776. if (options.radius !== undefined) {
  63777. radius = options.radius;
  63778. }
  63779. ;
  63780. var tessellation = options.tessellation || 64 | 0;
  63781. var radiusFunction = options.radiusFunction || null;
  63782. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63783. var invertUV = options.invertUV || false;
  63784. var updatable = options.updatable;
  63785. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63786. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  63787. // tube geometry
  63788. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  63789. var tangents = path3D.getTangents();
  63790. var normals = path3D.getNormals();
  63791. var distances = path3D.getDistances();
  63792. var pi2 = Math.PI * 2;
  63793. var step = pi2 / tessellation * arc;
  63794. var returnRadius = function () { return radius; };
  63795. var radiusFunctionFinal = radiusFunction || returnRadius;
  63796. var circlePath;
  63797. var rad;
  63798. var normal;
  63799. var rotated;
  63800. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63801. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63802. for (var i = 0; i < path.length; i++) {
  63803. rad = radiusFunctionFinal(i, distances[i]); // current radius
  63804. circlePath = Array(); // current circle array
  63805. normal = normals[i]; // current normal
  63806. for (var t = 0; t < tessellation; t++) {
  63807. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  63808. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  63809. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  63810. rotated.scaleInPlace(rad).addInPlace(path[i]);
  63811. circlePath[t] = rotated;
  63812. }
  63813. circlePaths[index] = circlePath;
  63814. index++;
  63815. }
  63816. // cap
  63817. var capPath = function (nbPoints, pathIndex) {
  63818. var pointCap = Array();
  63819. for (var i = 0; i < nbPoints; i++) {
  63820. pointCap.push(path[pathIndex]);
  63821. }
  63822. return pointCap;
  63823. };
  63824. switch (cap) {
  63825. case BABYLON.Mesh.NO_CAP:
  63826. break;
  63827. case BABYLON.Mesh.CAP_START:
  63828. circlePaths[0] = capPath(tessellation, 0);
  63829. circlePaths[1] = circlePaths[2].slice(0);
  63830. break;
  63831. case BABYLON.Mesh.CAP_END:
  63832. circlePaths[index] = circlePaths[index - 1].slice(0);
  63833. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63834. break;
  63835. case BABYLON.Mesh.CAP_ALL:
  63836. circlePaths[0] = capPath(tessellation, 0);
  63837. circlePaths[1] = circlePaths[2].slice(0);
  63838. circlePaths[index] = circlePaths[index - 1].slice(0);
  63839. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63840. break;
  63841. default:
  63842. break;
  63843. }
  63844. return circlePaths;
  63845. };
  63846. var path3D;
  63847. var pathArray;
  63848. if (instance) { // tube update
  63849. var arc = options.arc || instance.arc;
  63850. path3D = (instance.path3D).update(path);
  63851. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63852. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63853. instance.path3D = path3D;
  63854. instance.pathArray = pathArray;
  63855. instance.arc = arc;
  63856. instance.radius = radius;
  63857. return instance;
  63858. }
  63859. // tube creation
  63860. path3D = new BABYLON.Path3D(path);
  63861. var newPathArray = new Array();
  63862. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63863. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63864. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63865. tube.pathArray = pathArray;
  63866. tube.path3D = path3D;
  63867. tube.tessellation = tessellation;
  63868. tube.cap = cap;
  63869. tube.arc = options.arc;
  63870. tube.radius = radius;
  63871. return tube;
  63872. };
  63873. /**
  63874. * Creates a polyhedron mesh
  63875. * * 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
  63876. * * The parameter `size` (positive float, default 1) sets the polygon size
  63877. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63878. * * 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`
  63879. * * 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
  63880. * * 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)`)
  63881. * * 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
  63882. * * 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
  63883. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63884. * * 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
  63885. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63886. * @param name defines the name of the mesh
  63887. * @param options defines the options used to create the mesh
  63888. * @param scene defines the hosting scene
  63889. * @returns the polyhedron mesh
  63890. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63891. */
  63892. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63893. var polyhedron = new BABYLON.Mesh(name, scene);
  63894. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63895. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63896. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63897. vertexData.applyToMesh(polyhedron, options.updatable);
  63898. return polyhedron;
  63899. };
  63900. /**
  63901. * Creates a decal mesh.
  63902. * 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
  63903. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63904. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63905. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63906. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63907. * @param name defines the name of the mesh
  63908. * @param sourceMesh defines the mesh where the decal must be applied
  63909. * @param options defines the options used to create the mesh
  63910. * @param scene defines the hosting scene
  63911. * @returns the decal mesh
  63912. * @see http://doc.babylonjs.com/how_to/decals
  63913. */
  63914. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63915. var indices = sourceMesh.getIndices();
  63916. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63917. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63918. var position = options.position || BABYLON.Vector3.Zero();
  63919. var normal = options.normal || BABYLON.Vector3.Up();
  63920. var size = options.size || BABYLON.Vector3.One();
  63921. var angle = options.angle || 0;
  63922. // Getting correct rotation
  63923. if (!normal) {
  63924. var target = new BABYLON.Vector3(0, 0, 1);
  63925. var camera = sourceMesh.getScene().activeCamera;
  63926. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63927. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63928. }
  63929. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63930. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63931. var pitch = Math.atan2(normal.y, len);
  63932. // Matrix
  63933. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63934. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63935. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63936. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63937. var vertexData = new BABYLON.VertexData();
  63938. vertexData.indices = [];
  63939. vertexData.positions = [];
  63940. vertexData.normals = [];
  63941. vertexData.uvs = [];
  63942. var currentVertexDataIndex = 0;
  63943. var extractDecalVector3 = function (indexId) {
  63944. var result = new BABYLON.PositionNormalVertex();
  63945. if (!indices || !positions || !normals) {
  63946. return result;
  63947. }
  63948. var vertexId = indices[indexId];
  63949. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63950. // Send vector to decal local world
  63951. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63952. // Get normal
  63953. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63954. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63955. return result;
  63956. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63957. var clip = function (vertices, axis) {
  63958. if (vertices.length === 0) {
  63959. return vertices;
  63960. }
  63961. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63962. var clipVertices = function (v0, v1) {
  63963. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63964. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63965. };
  63966. var result = new Array();
  63967. for (var index = 0; index < vertices.length; index += 3) {
  63968. var v1Out;
  63969. var v2Out;
  63970. var v3Out;
  63971. var total = 0;
  63972. var nV1 = null;
  63973. var nV2 = null;
  63974. var nV3 = null;
  63975. var nV4 = null;
  63976. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63977. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63978. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63979. v1Out = d1 > 0;
  63980. v2Out = d2 > 0;
  63981. v3Out = d3 > 0;
  63982. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63983. switch (total) {
  63984. case 0:
  63985. result.push(vertices[index]);
  63986. result.push(vertices[index + 1]);
  63987. result.push(vertices[index + 2]);
  63988. break;
  63989. case 1:
  63990. if (v1Out) {
  63991. nV1 = vertices[index + 1];
  63992. nV2 = vertices[index + 2];
  63993. nV3 = clipVertices(vertices[index], nV1);
  63994. nV4 = clipVertices(vertices[index], nV2);
  63995. }
  63996. if (v2Out) {
  63997. nV1 = vertices[index];
  63998. nV2 = vertices[index + 2];
  63999. nV3 = clipVertices(vertices[index + 1], nV1);
  64000. nV4 = clipVertices(vertices[index + 1], nV2);
  64001. result.push(nV3);
  64002. result.push(nV2.clone());
  64003. result.push(nV1.clone());
  64004. result.push(nV2.clone());
  64005. result.push(nV3.clone());
  64006. result.push(nV4);
  64007. break;
  64008. }
  64009. if (v3Out) {
  64010. nV1 = vertices[index];
  64011. nV2 = vertices[index + 1];
  64012. nV3 = clipVertices(vertices[index + 2], nV1);
  64013. nV4 = clipVertices(vertices[index + 2], nV2);
  64014. }
  64015. if (nV1 && nV2 && nV3 && nV4) {
  64016. result.push(nV1.clone());
  64017. result.push(nV2.clone());
  64018. result.push(nV3);
  64019. result.push(nV4);
  64020. result.push(nV3.clone());
  64021. result.push(nV2.clone());
  64022. }
  64023. break;
  64024. case 2:
  64025. if (!v1Out) {
  64026. nV1 = vertices[index].clone();
  64027. nV2 = clipVertices(nV1, vertices[index + 1]);
  64028. nV3 = clipVertices(nV1, vertices[index + 2]);
  64029. result.push(nV1);
  64030. result.push(nV2);
  64031. result.push(nV3);
  64032. }
  64033. if (!v2Out) {
  64034. nV1 = vertices[index + 1].clone();
  64035. nV2 = clipVertices(nV1, vertices[index + 2]);
  64036. nV3 = clipVertices(nV1, vertices[index]);
  64037. result.push(nV1);
  64038. result.push(nV2);
  64039. result.push(nV3);
  64040. }
  64041. if (!v3Out) {
  64042. nV1 = vertices[index + 2].clone();
  64043. nV2 = clipVertices(nV1, vertices[index]);
  64044. nV3 = clipVertices(nV1, vertices[index + 1]);
  64045. result.push(nV1);
  64046. result.push(nV2);
  64047. result.push(nV3);
  64048. }
  64049. break;
  64050. case 3:
  64051. break;
  64052. }
  64053. }
  64054. return result;
  64055. };
  64056. for (var index = 0; index < indices.length; index += 3) {
  64057. var faceVertices = new Array();
  64058. faceVertices.push(extractDecalVector3(index));
  64059. faceVertices.push(extractDecalVector3(index + 1));
  64060. faceVertices.push(extractDecalVector3(index + 2));
  64061. // Clip
  64062. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64063. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64064. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64065. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64066. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64067. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64068. if (faceVertices.length === 0) {
  64069. continue;
  64070. }
  64071. // Add UVs and get back to world
  64072. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64073. var vertex = faceVertices[vIndex];
  64074. //TODO check for Int32Array | Uint32Array | Uint16Array
  64075. vertexData.indices.push(currentVertexDataIndex);
  64076. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64077. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64078. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64079. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64080. currentVertexDataIndex++;
  64081. }
  64082. }
  64083. // Return mesh
  64084. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64085. vertexData.applyToMesh(decal);
  64086. decal.position = position.clone();
  64087. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64088. return decal;
  64089. };
  64090. // Privates
  64091. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64092. // extrusion geometry
  64093. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64094. var tangents = path3D.getTangents();
  64095. var normals = path3D.getNormals();
  64096. var binormals = path3D.getBinormals();
  64097. var distances = path3D.getDistances();
  64098. var angle = 0;
  64099. var returnScale = function () { return scale !== null ? scale : 1; };
  64100. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64101. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64102. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64103. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64104. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64105. for (var i = 0; i < curve.length; i++) {
  64106. var shapePath = new Array();
  64107. var angleStep = rotate(i, distances[i]);
  64108. var scaleRatio = scl(i, distances[i]);
  64109. for (var p = 0; p < shape.length; p++) {
  64110. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64111. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64112. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64113. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64114. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64115. shapePath[p] = rotated;
  64116. }
  64117. shapePaths[index] = shapePath;
  64118. angle += angleStep;
  64119. index++;
  64120. }
  64121. // cap
  64122. var capPath = function (shapePath) {
  64123. var pointCap = Array();
  64124. var barycenter = BABYLON.Vector3.Zero();
  64125. var i;
  64126. for (i = 0; i < shapePath.length; i++) {
  64127. barycenter.addInPlace(shapePath[i]);
  64128. }
  64129. barycenter.scaleInPlace(1.0 / shapePath.length);
  64130. for (i = 0; i < shapePath.length; i++) {
  64131. pointCap.push(barycenter);
  64132. }
  64133. return pointCap;
  64134. };
  64135. switch (cap) {
  64136. case BABYLON.Mesh.NO_CAP:
  64137. break;
  64138. case BABYLON.Mesh.CAP_START:
  64139. shapePaths[0] = capPath(shapePaths[2]);
  64140. shapePaths[1] = shapePaths[2];
  64141. break;
  64142. case BABYLON.Mesh.CAP_END:
  64143. shapePaths[index] = shapePaths[index - 1];
  64144. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64145. break;
  64146. case BABYLON.Mesh.CAP_ALL:
  64147. shapePaths[0] = capPath(shapePaths[2]);
  64148. shapePaths[1] = shapePaths[2];
  64149. shapePaths[index] = shapePaths[index - 1];
  64150. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64151. break;
  64152. default:
  64153. break;
  64154. }
  64155. return shapePaths;
  64156. };
  64157. var path3D;
  64158. var pathArray;
  64159. if (instance) { // instance update
  64160. path3D = (instance.path3D).update(curve);
  64161. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64162. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64163. return instance;
  64164. }
  64165. // extruded shape creation
  64166. path3D = new BABYLON.Path3D(curve);
  64167. var newShapePaths = new Array();
  64168. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64169. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64170. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64171. extrudedGeneric.pathArray = pathArray;
  64172. extrudedGeneric.path3D = path3D;
  64173. extrudedGeneric.cap = cap;
  64174. return extrudedGeneric;
  64175. };
  64176. return MeshBuilder;
  64177. }());
  64178. BABYLON.MeshBuilder = MeshBuilder;
  64179. })(BABYLON || (BABYLON = {}));
  64180. //# sourceMappingURL=babylon.meshBuilder.js.map
  64181. var BABYLON;
  64182. (function (BABYLON) {
  64183. /**
  64184. * Draco compression (https://google.github.io/draco/)
  64185. *
  64186. * This class wraps the Draco module.
  64187. *
  64188. * **Encoder**
  64189. *
  64190. * The encoder is not currently implemented.
  64191. *
  64192. * **Decoder**
  64193. *
  64194. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64195. *
  64196. * To update the configuration, use the following code:
  64197. * ```javascript
  64198. * BABYLON.DracoCompression.Configuration = {
  64199. * decoder: {
  64200. * wasmUrl: "<url to the WebAssembly library>",
  64201. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64202. * fallbackUrl: "<url to the fallback JavaScript library>",
  64203. * }
  64204. * };
  64205. * ```
  64206. *
  64207. * 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.
  64208. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64209. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64210. *
  64211. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64212. * ```javascript
  64213. * var dracoCompression = new BABYLON.DracoCompression();
  64214. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64215. * [BABYLON.VertexBuffer.PositionKind]: 0
  64216. * });
  64217. * ```
  64218. *
  64219. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64220. */
  64221. var DracoCompression = /** @class */ (function () {
  64222. /**
  64223. * Constructor
  64224. */
  64225. function DracoCompression() {
  64226. }
  64227. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64228. /**
  64229. * Returns true if the decoder is available.
  64230. */
  64231. get: function () {
  64232. if (typeof DracoDecoderModule !== "undefined") {
  64233. return true;
  64234. }
  64235. var decoder = DracoCompression.Configuration.decoder;
  64236. if (decoder) {
  64237. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64238. return true;
  64239. }
  64240. if (decoder.fallbackUrl) {
  64241. return true;
  64242. }
  64243. }
  64244. return false;
  64245. },
  64246. enumerable: true,
  64247. configurable: true
  64248. });
  64249. /**
  64250. * Stop all async operations and release resources.
  64251. */
  64252. DracoCompression.prototype.dispose = function () {
  64253. };
  64254. /**
  64255. * Decode Draco compressed mesh data to vertex data.
  64256. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64257. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64258. * @returns A promise that resolves with the decoded vertex data
  64259. */
  64260. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64261. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64262. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64263. var module = wrappedModule.module;
  64264. var vertexData = new BABYLON.VertexData();
  64265. var buffer = new module.DecoderBuffer();
  64266. buffer.Init(dataView, dataView.byteLength);
  64267. var decoder = new module.Decoder();
  64268. var geometry;
  64269. var status;
  64270. try {
  64271. var type = decoder.GetEncodedGeometryType(buffer);
  64272. switch (type) {
  64273. case module.TRIANGULAR_MESH:
  64274. geometry = new module.Mesh();
  64275. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64276. break;
  64277. case module.POINT_CLOUD:
  64278. geometry = new module.PointCloud();
  64279. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64280. break;
  64281. default:
  64282. throw new Error("Invalid geometry type " + type);
  64283. }
  64284. if (!status.ok() || !geometry.ptr) {
  64285. throw new Error(status.error_msg());
  64286. }
  64287. var numPoints = geometry.num_points();
  64288. if (type === module.TRIANGULAR_MESH) {
  64289. var numFaces = geometry.num_faces();
  64290. var faceIndices = new module.DracoInt32Array();
  64291. try {
  64292. var indices = new Uint32Array(numFaces * 3);
  64293. for (var i = 0; i < numFaces; i++) {
  64294. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64295. var offset = i * 3;
  64296. indices[offset + 0] = faceIndices.GetValue(0);
  64297. indices[offset + 1] = faceIndices.GetValue(1);
  64298. indices[offset + 2] = faceIndices.GetValue(2);
  64299. }
  64300. vertexData.indices = indices;
  64301. }
  64302. finally {
  64303. module.destroy(faceIndices);
  64304. }
  64305. }
  64306. for (var kind in attributes) {
  64307. var uniqueId = attributes[kind];
  64308. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64309. var dracoData = new module.DracoFloat32Array();
  64310. try {
  64311. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64312. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64313. for (var i = 0; i < babylonData.length; i++) {
  64314. babylonData[i] = dracoData.GetValue(i);
  64315. }
  64316. vertexData.set(babylonData, kind);
  64317. }
  64318. finally {
  64319. module.destroy(dracoData);
  64320. }
  64321. }
  64322. }
  64323. finally {
  64324. if (geometry) {
  64325. module.destroy(geometry);
  64326. }
  64327. module.destroy(decoder);
  64328. module.destroy(buffer);
  64329. }
  64330. return vertexData;
  64331. });
  64332. };
  64333. DracoCompression._GetDecoderModule = function () {
  64334. if (!DracoCompression._DecoderModulePromise) {
  64335. var promise = null;
  64336. var config_1 = {};
  64337. if (typeof DracoDecoderModule !== "undefined") {
  64338. promise = Promise.resolve();
  64339. }
  64340. else {
  64341. var decoder = DracoCompression.Configuration.decoder;
  64342. if (decoder) {
  64343. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64344. promise = Promise.all([
  64345. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64346. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64347. config_1.wasmBinary = data;
  64348. })
  64349. ]);
  64350. }
  64351. else if (decoder.fallbackUrl) {
  64352. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64353. }
  64354. }
  64355. }
  64356. if (!promise) {
  64357. throw new Error("Draco decoder module is not available");
  64358. }
  64359. DracoCompression._DecoderModulePromise = promise.then(function () {
  64360. return new Promise(function (resolve) {
  64361. config_1.onModuleLoaded = function (decoderModule) {
  64362. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64363. resolve({ module: decoderModule });
  64364. };
  64365. DracoDecoderModule(config_1);
  64366. });
  64367. });
  64368. }
  64369. return DracoCompression._DecoderModulePromise;
  64370. };
  64371. DracoCompression._LoadScriptAsync = function (url) {
  64372. return new Promise(function (resolve, reject) {
  64373. BABYLON.Tools.LoadScript(url, function () {
  64374. resolve();
  64375. }, function (message) {
  64376. reject(new Error(message));
  64377. });
  64378. });
  64379. };
  64380. DracoCompression._LoadFileAsync = function (url) {
  64381. return new Promise(function (resolve, reject) {
  64382. BABYLON.Tools.LoadFile(url, function (data) {
  64383. resolve(data);
  64384. }, undefined, undefined, true, function (request, exception) {
  64385. reject(exception);
  64386. });
  64387. });
  64388. };
  64389. /**
  64390. * The configuration. Defaults to the following urls:
  64391. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64392. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64393. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64394. */
  64395. DracoCompression.Configuration = {
  64396. decoder: {
  64397. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64398. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64399. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64400. }
  64401. };
  64402. return DracoCompression;
  64403. }());
  64404. BABYLON.DracoCompression = DracoCompression;
  64405. })(BABYLON || (BABYLON = {}));
  64406. //# sourceMappingURL=babylon.dracoCompression.js.map
  64407. var BABYLON;
  64408. (function (BABYLON) {
  64409. var AudioEngine = /** @class */ (function () {
  64410. function AudioEngine() {
  64411. this._audioContext = null;
  64412. this._audioContextInitialized = false;
  64413. this.canUseWebAudio = false;
  64414. this.WarnedWebAudioUnsupported = false;
  64415. this.unlocked = false;
  64416. this.isMP3supported = false;
  64417. this.isOGGsupported = false;
  64418. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64419. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64420. this.canUseWebAudio = true;
  64421. }
  64422. var audioElem = document.createElement('audio');
  64423. try {
  64424. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64425. this.isMP3supported = true;
  64426. }
  64427. }
  64428. catch (e) {
  64429. // protect error during capability check.
  64430. }
  64431. try {
  64432. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64433. this.isOGGsupported = true;
  64434. }
  64435. }
  64436. catch (e) {
  64437. // protect error during capability check.
  64438. }
  64439. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64440. this._unlockiOSaudio();
  64441. }
  64442. else {
  64443. this.unlocked = true;
  64444. }
  64445. }
  64446. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64447. get: function () {
  64448. if (!this._audioContextInitialized) {
  64449. this._initializeAudioContext();
  64450. }
  64451. return this._audioContext;
  64452. },
  64453. enumerable: true,
  64454. configurable: true
  64455. });
  64456. AudioEngine.prototype._unlockiOSaudio = function () {
  64457. var _this = this;
  64458. var unlockaudio = function () {
  64459. if (!_this.audioContext) {
  64460. return;
  64461. }
  64462. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64463. var source = _this.audioContext.createBufferSource();
  64464. source.buffer = buffer;
  64465. source.connect(_this.audioContext.destination);
  64466. source.start(0);
  64467. setTimeout(function () {
  64468. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64469. _this.unlocked = true;
  64470. window.removeEventListener('touchend', unlockaudio, false);
  64471. if (_this.onAudioUnlocked) {
  64472. _this.onAudioUnlocked();
  64473. }
  64474. }
  64475. }, 0);
  64476. };
  64477. window.addEventListener('touchend', unlockaudio, false);
  64478. };
  64479. AudioEngine.prototype._initializeAudioContext = function () {
  64480. try {
  64481. if (this.canUseWebAudio) {
  64482. this._audioContext = new AudioContext();
  64483. // create a global volume gain node
  64484. this.masterGain = this._audioContext.createGain();
  64485. this.masterGain.gain.value = 1;
  64486. this.masterGain.connect(this._audioContext.destination);
  64487. this._audioContextInitialized = true;
  64488. }
  64489. }
  64490. catch (e) {
  64491. this.canUseWebAudio = false;
  64492. BABYLON.Tools.Error("Web Audio: " + e.message);
  64493. }
  64494. };
  64495. AudioEngine.prototype.dispose = function () {
  64496. if (this.canUseWebAudio && this._audioContextInitialized) {
  64497. if (this._connectedAnalyser && this._audioContext) {
  64498. this._connectedAnalyser.stopDebugCanvas();
  64499. this._connectedAnalyser.dispose();
  64500. this.masterGain.disconnect();
  64501. this.masterGain.connect(this._audioContext.destination);
  64502. this._connectedAnalyser = null;
  64503. }
  64504. this.masterGain.gain.value = 1;
  64505. }
  64506. this.WarnedWebAudioUnsupported = false;
  64507. };
  64508. AudioEngine.prototype.getGlobalVolume = function () {
  64509. if (this.canUseWebAudio && this._audioContextInitialized) {
  64510. return this.masterGain.gain.value;
  64511. }
  64512. else {
  64513. return -1;
  64514. }
  64515. };
  64516. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64517. if (this.canUseWebAudio && this._audioContextInitialized) {
  64518. this.masterGain.gain.value = newVolume;
  64519. }
  64520. };
  64521. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64522. if (this._connectedAnalyser) {
  64523. this._connectedAnalyser.stopDebugCanvas();
  64524. }
  64525. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64526. this._connectedAnalyser = analyser;
  64527. this.masterGain.disconnect();
  64528. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64529. }
  64530. };
  64531. return AudioEngine;
  64532. }());
  64533. BABYLON.AudioEngine = AudioEngine;
  64534. })(BABYLON || (BABYLON = {}));
  64535. //# sourceMappingURL=babylon.audioEngine.js.map
  64536. var BABYLON;
  64537. (function (BABYLON) {
  64538. var Sound = /** @class */ (function () {
  64539. /**
  64540. * Create a sound and attach it to a scene
  64541. * @param name Name of your sound
  64542. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64543. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64544. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64545. */
  64546. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64547. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64548. var _this = this;
  64549. this.autoplay = false;
  64550. this.loop = false;
  64551. this.useCustomAttenuation = false;
  64552. this.spatialSound = false;
  64553. this.refDistance = 1;
  64554. this.rolloffFactor = 1;
  64555. this.maxDistance = 100;
  64556. this.distanceModel = "linear";
  64557. this._panningModel = "equalpower";
  64558. /**
  64559. * Observable event when the current playing sound finishes.
  64560. */
  64561. this.onEndedObservable = new BABYLON.Observable();
  64562. this._playbackRate = 1;
  64563. this._streaming = false;
  64564. this._startTime = 0;
  64565. this._startOffset = 0;
  64566. this._position = BABYLON.Vector3.Zero();
  64567. /** @hidden */
  64568. this._positionInEmitterSpace = false;
  64569. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64570. this._volume = 1;
  64571. this._isReadyToPlay = false;
  64572. this.isPlaying = false;
  64573. this.isPaused = false;
  64574. this._isDirectional = false;
  64575. // Used if you'd like to create a directional sound.
  64576. // If not set, the sound will be omnidirectional
  64577. this._coneInnerAngle = 360;
  64578. this._coneOuterAngle = 360;
  64579. this._coneOuterGain = 0;
  64580. this._isOutputConnected = false;
  64581. this._urlType = "Unknown";
  64582. this.name = name;
  64583. this._scene = scene;
  64584. this._readyToPlayCallback = readyToPlayCallback;
  64585. // Default custom attenuation function is a linear attenuation
  64586. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64587. if (currentDistance < maxDistance) {
  64588. return currentVolume * (1 - currentDistance / maxDistance);
  64589. }
  64590. else {
  64591. return 0;
  64592. }
  64593. };
  64594. if (options) {
  64595. this.autoplay = options.autoplay || false;
  64596. this.loop = options.loop || false;
  64597. // if volume === 0, we need another way to check this option
  64598. if (options.volume !== undefined) {
  64599. this._volume = options.volume;
  64600. }
  64601. this.spatialSound = options.spatialSound || false;
  64602. this.maxDistance = options.maxDistance || 100;
  64603. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64604. this.rolloffFactor = options.rolloffFactor || 1;
  64605. this.refDistance = options.refDistance || 1;
  64606. this.distanceModel = options.distanceModel || "linear";
  64607. this._playbackRate = options.playbackRate || 1;
  64608. this._streaming = options.streaming || false;
  64609. }
  64610. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64611. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64612. this._soundGain.gain.value = this._volume;
  64613. this._inputAudioNode = this._soundGain;
  64614. this._outputAudioNode = this._soundGain;
  64615. if (this.spatialSound) {
  64616. this._createSpatialParameters();
  64617. }
  64618. this._scene.mainSoundTrack.AddSound(this);
  64619. var validParameter = true;
  64620. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64621. if (urlOrArrayBuffer) {
  64622. try {
  64623. if (typeof (urlOrArrayBuffer) === "string") {
  64624. this._urlType = "String";
  64625. }
  64626. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64627. this._urlType = "ArrayBuffer";
  64628. }
  64629. else if (urlOrArrayBuffer instanceof MediaStream) {
  64630. this._urlType = "MediaStream";
  64631. }
  64632. else if (Array.isArray(urlOrArrayBuffer)) {
  64633. this._urlType = "Array";
  64634. }
  64635. var urls = [];
  64636. var codecSupportedFound = false;
  64637. switch (this._urlType) {
  64638. case "MediaStream":
  64639. this._streaming = true;
  64640. this._isReadyToPlay = true;
  64641. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  64642. if (this.autoplay) {
  64643. this.play();
  64644. }
  64645. if (this._readyToPlayCallback) {
  64646. this._readyToPlayCallback();
  64647. }
  64648. break;
  64649. case "ArrayBuffer":
  64650. if (urlOrArrayBuffer.byteLength > 0) {
  64651. codecSupportedFound = true;
  64652. this._soundLoaded(urlOrArrayBuffer);
  64653. }
  64654. break;
  64655. case "String":
  64656. urls.push(urlOrArrayBuffer);
  64657. case "Array":
  64658. if (urls.length === 0)
  64659. urls = urlOrArrayBuffer;
  64660. // If we found a supported format, we load it immediately and stop the loop
  64661. for (var i = 0; i < urls.length; i++) {
  64662. var url = urls[i];
  64663. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64664. codecSupportedFound = true;
  64665. }
  64666. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64667. codecSupportedFound = true;
  64668. }
  64669. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64670. codecSupportedFound = true;
  64671. }
  64672. if (url.indexOf("blob:") !== -1) {
  64673. codecSupportedFound = true;
  64674. }
  64675. if (codecSupportedFound) {
  64676. // Loading sound using XHR2
  64677. if (!this._streaming) {
  64678. this._scene._loadFile(url, function (data) {
  64679. _this._soundLoaded(data);
  64680. }, undefined, true, true, function (exception) {
  64681. if (exception) {
  64682. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64683. }
  64684. BABYLON.Tools.Error("Sound creation aborted.");
  64685. _this._scene.mainSoundTrack.RemoveSound(_this);
  64686. });
  64687. }
  64688. // Streaming sound using HTML5 Audio tag
  64689. else {
  64690. this._htmlAudioElement = new Audio(url);
  64691. this._htmlAudioElement.controls = false;
  64692. this._htmlAudioElement.loop = this.loop;
  64693. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64694. this._htmlAudioElement.preload = "auto";
  64695. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64696. _this._isReadyToPlay = true;
  64697. if (_this.autoplay) {
  64698. _this.play();
  64699. }
  64700. if (_this._readyToPlayCallback) {
  64701. _this._readyToPlayCallback();
  64702. }
  64703. });
  64704. document.body.appendChild(this._htmlAudioElement);
  64705. }
  64706. break;
  64707. }
  64708. }
  64709. break;
  64710. default:
  64711. validParameter = false;
  64712. break;
  64713. }
  64714. if (!validParameter) {
  64715. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64716. }
  64717. else {
  64718. if (!codecSupportedFound) {
  64719. this._isReadyToPlay = true;
  64720. // Simulating a ready to play event to avoid breaking code path
  64721. if (this._readyToPlayCallback) {
  64722. window.setTimeout(function () {
  64723. if (_this._readyToPlayCallback) {
  64724. _this._readyToPlayCallback();
  64725. }
  64726. }, 1000);
  64727. }
  64728. }
  64729. }
  64730. }
  64731. catch (ex) {
  64732. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64733. this._scene.mainSoundTrack.RemoveSound(this);
  64734. }
  64735. }
  64736. }
  64737. else {
  64738. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64739. this._scene.mainSoundTrack.AddSound(this);
  64740. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64741. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64742. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64743. }
  64744. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64745. if (this._readyToPlayCallback) {
  64746. window.setTimeout(function () {
  64747. if (_this._readyToPlayCallback) {
  64748. _this._readyToPlayCallback();
  64749. }
  64750. }, 1000);
  64751. }
  64752. }
  64753. }
  64754. Sound.prototype.dispose = function () {
  64755. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64756. if (this.isPlaying) {
  64757. this.stop();
  64758. }
  64759. this._isReadyToPlay = false;
  64760. if (this.soundTrackId === -1) {
  64761. this._scene.mainSoundTrack.RemoveSound(this);
  64762. }
  64763. else {
  64764. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64765. }
  64766. if (this._soundGain) {
  64767. this._soundGain.disconnect();
  64768. this._soundGain = null;
  64769. }
  64770. if (this._soundPanner) {
  64771. this._soundPanner.disconnect();
  64772. this._soundPanner = null;
  64773. }
  64774. if (this._soundSource) {
  64775. this._soundSource.disconnect();
  64776. this._soundSource = null;
  64777. }
  64778. this._audioBuffer = null;
  64779. if (this._htmlAudioElement) {
  64780. this._htmlAudioElement.pause();
  64781. this._htmlAudioElement.src = "";
  64782. document.body.removeChild(this._htmlAudioElement);
  64783. }
  64784. if (this._streamingSource) {
  64785. this._streamingSource.disconnect();
  64786. }
  64787. if (this._connectedMesh && this._registerFunc) {
  64788. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64789. this._connectedMesh = null;
  64790. }
  64791. }
  64792. };
  64793. Sound.prototype.isReady = function () {
  64794. return this._isReadyToPlay;
  64795. };
  64796. Sound.prototype._soundLoaded = function (audioData) {
  64797. var _this = this;
  64798. if (!BABYLON.Engine.audioEngine.audioContext) {
  64799. return;
  64800. }
  64801. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  64802. _this._audioBuffer = buffer;
  64803. _this._isReadyToPlay = true;
  64804. if (_this.autoplay) {
  64805. _this.play();
  64806. }
  64807. if (_this._readyToPlayCallback) {
  64808. _this._readyToPlayCallback();
  64809. }
  64810. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  64811. };
  64812. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  64813. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64814. this._audioBuffer = audioBuffer;
  64815. this._isReadyToPlay = true;
  64816. }
  64817. };
  64818. Sound.prototype.updateOptions = function (options) {
  64819. if (options) {
  64820. this.loop = options.loop || this.loop;
  64821. this.maxDistance = options.maxDistance || this.maxDistance;
  64822. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  64823. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  64824. this.refDistance = options.refDistance || this.refDistance;
  64825. this.distanceModel = options.distanceModel || this.distanceModel;
  64826. this._playbackRate = options.playbackRate || this._playbackRate;
  64827. this._updateSpatialParameters();
  64828. if (this.isPlaying) {
  64829. if (this._streaming && this._htmlAudioElement) {
  64830. this._htmlAudioElement.playbackRate = this._playbackRate;
  64831. }
  64832. else {
  64833. if (this._soundSource) {
  64834. this._soundSource.playbackRate.value = this._playbackRate;
  64835. }
  64836. }
  64837. }
  64838. }
  64839. };
  64840. Sound.prototype._createSpatialParameters = function () {
  64841. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64842. if (this._scene.headphone) {
  64843. this._panningModel = "HRTF";
  64844. }
  64845. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64846. this._updateSpatialParameters();
  64847. this._soundPanner.connect(this._outputAudioNode);
  64848. this._inputAudioNode = this._soundPanner;
  64849. }
  64850. };
  64851. Sound.prototype._updateSpatialParameters = function () {
  64852. if (this.spatialSound && this._soundPanner) {
  64853. if (this.useCustomAttenuation) {
  64854. // Tricks to disable in a way embedded Web Audio attenuation
  64855. this._soundPanner.distanceModel = "linear";
  64856. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64857. this._soundPanner.refDistance = 1;
  64858. this._soundPanner.rolloffFactor = 1;
  64859. this._soundPanner.panningModel = this._panningModel;
  64860. }
  64861. else {
  64862. this._soundPanner.distanceModel = this.distanceModel;
  64863. this._soundPanner.maxDistance = this.maxDistance;
  64864. this._soundPanner.refDistance = this.refDistance;
  64865. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64866. this._soundPanner.panningModel = this._panningModel;
  64867. }
  64868. }
  64869. };
  64870. Sound.prototype.switchPanningModelToHRTF = function () {
  64871. this._panningModel = "HRTF";
  64872. this._switchPanningModel();
  64873. };
  64874. Sound.prototype.switchPanningModelToEqualPower = function () {
  64875. this._panningModel = "equalpower";
  64876. this._switchPanningModel();
  64877. };
  64878. Sound.prototype._switchPanningModel = function () {
  64879. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64880. this._soundPanner.panningModel = this._panningModel;
  64881. }
  64882. };
  64883. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64884. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64885. if (this._isOutputConnected) {
  64886. this._outputAudioNode.disconnect();
  64887. }
  64888. this._outputAudioNode.connect(soundTrackAudioNode);
  64889. this._isOutputConnected = true;
  64890. }
  64891. };
  64892. /**
  64893. * Transform this sound into a directional source
  64894. * @param coneInnerAngle Size of the inner cone in degree
  64895. * @param coneOuterAngle Size of the outer cone in degree
  64896. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64897. */
  64898. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64899. if (coneOuterAngle < coneInnerAngle) {
  64900. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64901. return;
  64902. }
  64903. this._coneInnerAngle = coneInnerAngle;
  64904. this._coneOuterAngle = coneOuterAngle;
  64905. this._coneOuterGain = coneOuterGain;
  64906. this._isDirectional = true;
  64907. if (this.isPlaying && this.loop) {
  64908. this.stop();
  64909. this.play();
  64910. }
  64911. };
  64912. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  64913. /**
  64914. * Gets or sets the inner angle for the directional cone.
  64915. */
  64916. get: function () {
  64917. return this._coneInnerAngle;
  64918. },
  64919. /**
  64920. * Gets or sets the inner angle for the directional cone.
  64921. */
  64922. set: function (value) {
  64923. if (value != this._coneInnerAngle) {
  64924. if (this._coneOuterAngle < value) {
  64925. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64926. return;
  64927. }
  64928. this._coneInnerAngle = value;
  64929. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64930. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64931. }
  64932. }
  64933. },
  64934. enumerable: true,
  64935. configurable: true
  64936. });
  64937. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  64938. /**
  64939. * Gets or sets the outer angle for the directional cone.
  64940. */
  64941. get: function () {
  64942. return this._coneOuterAngle;
  64943. },
  64944. /**
  64945. * Gets or sets the outer angle for the directional cone.
  64946. */
  64947. set: function (value) {
  64948. if (value != this._coneOuterAngle) {
  64949. if (value < this._coneInnerAngle) {
  64950. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64951. return;
  64952. }
  64953. this._coneOuterAngle = value;
  64954. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64955. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64956. }
  64957. }
  64958. },
  64959. enumerable: true,
  64960. configurable: true
  64961. });
  64962. Sound.prototype.setPosition = function (newPosition) {
  64963. this._position = newPosition;
  64964. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64965. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64966. }
  64967. };
  64968. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64969. this._localDirection = newLocalDirection;
  64970. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64971. this._updateDirection();
  64972. }
  64973. };
  64974. Sound.prototype._updateDirection = function () {
  64975. if (!this._connectedMesh || !this._soundPanner) {
  64976. return;
  64977. }
  64978. var mat = this._connectedMesh.getWorldMatrix();
  64979. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64980. direction.normalize();
  64981. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64982. };
  64983. Sound.prototype.updateDistanceFromListener = function () {
  64984. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64985. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64986. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64987. }
  64988. };
  64989. Sound.prototype.setAttenuationFunction = function (callback) {
  64990. this._customAttenuationFunction = callback;
  64991. };
  64992. /**
  64993. * Play the sound
  64994. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64995. * @param offset (optional) Start the sound setting it at a specific time
  64996. */
  64997. Sound.prototype.play = function (time, offset) {
  64998. var _this = this;
  64999. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65000. try {
  65001. if (this._startOffset < 0) {
  65002. time = -this._startOffset;
  65003. this._startOffset = 0;
  65004. }
  65005. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65006. if (!this._soundSource || !this._streamingSource) {
  65007. if (this.spatialSound && this._soundPanner) {
  65008. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65009. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65010. }
  65011. if (this._isDirectional) {
  65012. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65013. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65014. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65015. if (this._connectedMesh) {
  65016. this._updateDirection();
  65017. }
  65018. else {
  65019. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65020. }
  65021. }
  65022. }
  65023. }
  65024. if (this._streaming) {
  65025. if (!this._streamingSource) {
  65026. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65027. this._htmlAudioElement.onended = function () { _this._onended(); };
  65028. this._htmlAudioElement.playbackRate = this._playbackRate;
  65029. }
  65030. this._streamingSource.disconnect();
  65031. this._streamingSource.connect(this._inputAudioNode);
  65032. if (this._htmlAudioElement) {
  65033. this._htmlAudioElement.play();
  65034. }
  65035. }
  65036. else {
  65037. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65038. this._soundSource.buffer = this._audioBuffer;
  65039. this._soundSource.connect(this._inputAudioNode);
  65040. this._soundSource.loop = this.loop;
  65041. this._soundSource.playbackRate.value = this._playbackRate;
  65042. this._soundSource.onended = function () { _this._onended(); };
  65043. if (this._soundSource.buffer) {
  65044. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65045. }
  65046. }
  65047. this._startTime = startTime;
  65048. this.isPlaying = true;
  65049. this.isPaused = false;
  65050. }
  65051. catch (ex) {
  65052. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65053. }
  65054. }
  65055. };
  65056. Sound.prototype._onended = function () {
  65057. this.isPlaying = false;
  65058. if (this.onended) {
  65059. this.onended();
  65060. }
  65061. this.onEndedObservable.notifyObservers(this);
  65062. };
  65063. /**
  65064. * Stop the sound
  65065. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65066. */
  65067. Sound.prototype.stop = function (time) {
  65068. if (this.isPlaying) {
  65069. if (this._streaming) {
  65070. if (this._htmlAudioElement) {
  65071. this._htmlAudioElement.pause();
  65072. // Test needed for Firefox or it will generate an Invalid State Error
  65073. if (this._htmlAudioElement.currentTime > 0) {
  65074. this._htmlAudioElement.currentTime = 0;
  65075. }
  65076. }
  65077. else {
  65078. this._streamingSource.disconnect();
  65079. }
  65080. }
  65081. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65082. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65083. this._soundSource.stop(stopTime);
  65084. this._soundSource.onended = function () { };
  65085. if (!this.isPaused) {
  65086. this._startOffset = 0;
  65087. }
  65088. }
  65089. this.isPlaying = false;
  65090. }
  65091. };
  65092. Sound.prototype.pause = function () {
  65093. if (this.isPlaying) {
  65094. this.isPaused = true;
  65095. if (this._streaming) {
  65096. if (this._htmlAudioElement) {
  65097. this._htmlAudioElement.pause();
  65098. }
  65099. else {
  65100. this._streamingSource.disconnect();
  65101. }
  65102. }
  65103. else if (BABYLON.Engine.audioEngine.audioContext) {
  65104. this.stop(0);
  65105. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65106. }
  65107. }
  65108. };
  65109. Sound.prototype.setVolume = function (newVolume, time) {
  65110. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65111. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65112. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65113. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65114. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65115. }
  65116. else {
  65117. this._soundGain.gain.value = newVolume;
  65118. }
  65119. }
  65120. this._volume = newVolume;
  65121. };
  65122. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65123. this._playbackRate = newPlaybackRate;
  65124. if (this.isPlaying) {
  65125. if (this._streaming && this._htmlAudioElement) {
  65126. this._htmlAudioElement.playbackRate = this._playbackRate;
  65127. }
  65128. else if (this._soundSource) {
  65129. this._soundSource.playbackRate.value = this._playbackRate;
  65130. }
  65131. }
  65132. };
  65133. Sound.prototype.getVolume = function () {
  65134. return this._volume;
  65135. };
  65136. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65137. var _this = this;
  65138. if (this._connectedMesh && this._registerFunc) {
  65139. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65140. this._registerFunc = null;
  65141. }
  65142. this._connectedMesh = meshToConnectTo;
  65143. if (!this.spatialSound) {
  65144. this.spatialSound = true;
  65145. this._createSpatialParameters();
  65146. if (this.isPlaying && this.loop) {
  65147. this.stop();
  65148. this.play();
  65149. }
  65150. }
  65151. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65152. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65153. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65154. };
  65155. Sound.prototype.detachFromMesh = function () {
  65156. if (this._connectedMesh && this._registerFunc) {
  65157. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65158. this._registerFunc = null;
  65159. this._connectedMesh = null;
  65160. }
  65161. };
  65162. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65163. if (!node.getBoundingInfo) {
  65164. return;
  65165. }
  65166. var mesh = node;
  65167. if (this._positionInEmitterSpace) {
  65168. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65169. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65170. }
  65171. else {
  65172. var boundingInfo = mesh.getBoundingInfo();
  65173. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65174. }
  65175. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65176. this._updateDirection();
  65177. }
  65178. };
  65179. Sound.prototype.clone = function () {
  65180. var _this = this;
  65181. if (!this._streaming) {
  65182. var setBufferAndRun = function () {
  65183. if (_this._isReadyToPlay) {
  65184. clonedSound._audioBuffer = _this.getAudioBuffer();
  65185. clonedSound._isReadyToPlay = true;
  65186. if (clonedSound.autoplay) {
  65187. clonedSound.play();
  65188. }
  65189. }
  65190. else {
  65191. window.setTimeout(setBufferAndRun, 300);
  65192. }
  65193. };
  65194. var currentOptions = {
  65195. autoplay: this.autoplay, loop: this.loop,
  65196. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65197. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65198. refDistance: this.refDistance, distanceModel: this.distanceModel
  65199. };
  65200. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65201. if (this.useCustomAttenuation) {
  65202. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65203. }
  65204. clonedSound.setPosition(this._position);
  65205. clonedSound.setPlaybackRate(this._playbackRate);
  65206. setBufferAndRun();
  65207. return clonedSound;
  65208. }
  65209. // Can't clone a streaming sound
  65210. else {
  65211. return null;
  65212. }
  65213. };
  65214. Sound.prototype.getAudioBuffer = function () {
  65215. return this._audioBuffer;
  65216. };
  65217. Sound.prototype.serialize = function () {
  65218. var serializationObject = {
  65219. name: this.name,
  65220. url: this.name,
  65221. autoplay: this.autoplay,
  65222. loop: this.loop,
  65223. volume: this._volume,
  65224. spatialSound: this.spatialSound,
  65225. maxDistance: this.maxDistance,
  65226. rolloffFactor: this.rolloffFactor,
  65227. refDistance: this.refDistance,
  65228. distanceModel: this.distanceModel,
  65229. playbackRate: this._playbackRate,
  65230. panningModel: this._panningModel,
  65231. soundTrackId: this.soundTrackId
  65232. };
  65233. if (this.spatialSound) {
  65234. if (this._connectedMesh)
  65235. serializationObject.connectedMeshId = this._connectedMesh.id;
  65236. serializationObject.position = this._position.asArray();
  65237. serializationObject.refDistance = this.refDistance;
  65238. serializationObject.distanceModel = this.distanceModel;
  65239. serializationObject.isDirectional = this._isDirectional;
  65240. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65241. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65242. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65243. serializationObject.coneOuterGain = this._coneOuterGain;
  65244. }
  65245. return serializationObject;
  65246. };
  65247. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65248. var soundName = parsedSound.name;
  65249. var soundUrl;
  65250. if (parsedSound.url) {
  65251. soundUrl = rootUrl + parsedSound.url;
  65252. }
  65253. else {
  65254. soundUrl = rootUrl + soundName;
  65255. }
  65256. var options = {
  65257. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65258. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65259. rolloffFactor: parsedSound.rolloffFactor,
  65260. refDistance: parsedSound.refDistance,
  65261. distanceModel: parsedSound.distanceModel,
  65262. playbackRate: parsedSound.playbackRate
  65263. };
  65264. var newSound;
  65265. if (!sourceSound) {
  65266. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65267. scene._addPendingData(newSound);
  65268. }
  65269. else {
  65270. var setBufferAndRun = function () {
  65271. if (sourceSound._isReadyToPlay) {
  65272. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65273. newSound._isReadyToPlay = true;
  65274. if (newSound.autoplay) {
  65275. newSound.play();
  65276. }
  65277. }
  65278. else {
  65279. window.setTimeout(setBufferAndRun, 300);
  65280. }
  65281. };
  65282. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65283. setBufferAndRun();
  65284. }
  65285. if (parsedSound.position) {
  65286. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65287. newSound.setPosition(soundPosition);
  65288. }
  65289. if (parsedSound.isDirectional) {
  65290. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65291. if (parsedSound.localDirectionToMesh) {
  65292. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65293. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65294. }
  65295. }
  65296. if (parsedSound.connectedMeshId) {
  65297. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65298. if (connectedMesh) {
  65299. newSound.attachToMesh(connectedMesh);
  65300. }
  65301. }
  65302. return newSound;
  65303. };
  65304. return Sound;
  65305. }());
  65306. BABYLON.Sound = Sound;
  65307. })(BABYLON || (BABYLON = {}));
  65308. //# sourceMappingURL=babylon.sound.js.map
  65309. var BABYLON;
  65310. (function (BABYLON) {
  65311. var SoundTrack = /** @class */ (function () {
  65312. function SoundTrack(scene, options) {
  65313. this.id = -1;
  65314. this._isMainTrack = false;
  65315. this._isInitialized = false;
  65316. this._scene = scene;
  65317. this.soundCollection = new Array();
  65318. this._options = options;
  65319. if (!this._isMainTrack) {
  65320. this._scene.soundTracks.push(this);
  65321. this.id = this._scene.soundTracks.length - 1;
  65322. }
  65323. }
  65324. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65325. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65326. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65327. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65328. if (this._options) {
  65329. if (this._options.volume) {
  65330. this._outputAudioNode.gain.value = this._options.volume;
  65331. }
  65332. if (this._options.mainTrack) {
  65333. this._isMainTrack = this._options.mainTrack;
  65334. }
  65335. }
  65336. this._isInitialized = true;
  65337. }
  65338. };
  65339. SoundTrack.prototype.dispose = function () {
  65340. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65341. if (this._connectedAnalyser) {
  65342. this._connectedAnalyser.stopDebugCanvas();
  65343. }
  65344. while (this.soundCollection.length) {
  65345. this.soundCollection[0].dispose();
  65346. }
  65347. if (this._outputAudioNode) {
  65348. this._outputAudioNode.disconnect();
  65349. }
  65350. this._outputAudioNode = null;
  65351. }
  65352. };
  65353. SoundTrack.prototype.AddSound = function (sound) {
  65354. if (!this._isInitialized) {
  65355. this._initializeSoundTrackAudioGraph();
  65356. }
  65357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65358. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65359. }
  65360. if (sound.soundTrackId) {
  65361. if (sound.soundTrackId === -1) {
  65362. this._scene.mainSoundTrack.RemoveSound(sound);
  65363. }
  65364. else {
  65365. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65366. }
  65367. }
  65368. this.soundCollection.push(sound);
  65369. sound.soundTrackId = this.id;
  65370. };
  65371. SoundTrack.prototype.RemoveSound = function (sound) {
  65372. var index = this.soundCollection.indexOf(sound);
  65373. if (index !== -1) {
  65374. this.soundCollection.splice(index, 1);
  65375. }
  65376. };
  65377. SoundTrack.prototype.setVolume = function (newVolume) {
  65378. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65379. this._outputAudioNode.gain.value = newVolume;
  65380. }
  65381. };
  65382. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65383. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65384. for (var i = 0; i < this.soundCollection.length; i++) {
  65385. this.soundCollection[i].switchPanningModelToHRTF();
  65386. }
  65387. }
  65388. };
  65389. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65391. for (var i = 0; i < this.soundCollection.length; i++) {
  65392. this.soundCollection[i].switchPanningModelToEqualPower();
  65393. }
  65394. }
  65395. };
  65396. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65397. if (this._connectedAnalyser) {
  65398. this._connectedAnalyser.stopDebugCanvas();
  65399. }
  65400. this._connectedAnalyser = analyser;
  65401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65402. this._outputAudioNode.disconnect();
  65403. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65404. }
  65405. };
  65406. return SoundTrack;
  65407. }());
  65408. BABYLON.SoundTrack = SoundTrack;
  65409. })(BABYLON || (BABYLON = {}));
  65410. //# sourceMappingURL=babylon.soundtrack.js.map
  65411. var BABYLON;
  65412. (function (BABYLON) {
  65413. /**
  65414. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65415. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65416. */
  65417. var Analyser = /** @class */ (function () {
  65418. /**
  65419. * Creates a new analyser
  65420. * @param scene defines hosting scene
  65421. */
  65422. function Analyser(scene) {
  65423. /**
  65424. * Gets or sets the smoothing
  65425. * @ignorenaming
  65426. */
  65427. this.SMOOTHING = 0.75;
  65428. /**
  65429. * Gets or sets the FFT table size
  65430. * @ignorenaming
  65431. */
  65432. this.FFT_SIZE = 512;
  65433. /**
  65434. * Gets or sets the bar graph amplitude
  65435. * @ignorenaming
  65436. */
  65437. this.BARGRAPHAMPLITUDE = 256;
  65438. /**
  65439. * Gets or sets the position of the debug canvas
  65440. * @ignorenaming
  65441. */
  65442. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65443. /**
  65444. * Gets or sets the debug canvas size
  65445. * @ignorenaming
  65446. */
  65447. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65448. this._scene = scene;
  65449. this._audioEngine = BABYLON.Engine.audioEngine;
  65450. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65451. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65452. this._webAudioAnalyser.minDecibels = -140;
  65453. this._webAudioAnalyser.maxDecibels = 0;
  65454. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65455. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65456. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65457. }
  65458. }
  65459. /**
  65460. * Get the number of data values you will have to play with for the visualization
  65461. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65462. * @returns a number
  65463. */
  65464. Analyser.prototype.getFrequencyBinCount = function () {
  65465. if (this._audioEngine.canUseWebAudio) {
  65466. return this._webAudioAnalyser.frequencyBinCount;
  65467. }
  65468. else {
  65469. return 0;
  65470. }
  65471. };
  65472. /**
  65473. * Gets the current frequency data as a byte array
  65474. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65475. * @returns a Uint8Array
  65476. */
  65477. Analyser.prototype.getByteFrequencyData = function () {
  65478. if (this._audioEngine.canUseWebAudio) {
  65479. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65480. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65481. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65482. }
  65483. return this._byteFreqs;
  65484. };
  65485. /**
  65486. * Gets the current waveform as a byte array
  65487. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65488. * @returns a Uint8Array
  65489. */
  65490. Analyser.prototype.getByteTimeDomainData = function () {
  65491. if (this._audioEngine.canUseWebAudio) {
  65492. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65493. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65494. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65495. }
  65496. return this._byteTime;
  65497. };
  65498. /**
  65499. * Gets the current frequency data as a float array
  65500. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65501. * @returns a Float32Array
  65502. */
  65503. Analyser.prototype.getFloatFrequencyData = function () {
  65504. if (this._audioEngine.canUseWebAudio) {
  65505. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65506. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65507. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65508. }
  65509. return this._floatFreqs;
  65510. };
  65511. /**
  65512. * Renders the debug canvas
  65513. */
  65514. Analyser.prototype.drawDebugCanvas = function () {
  65515. var _this = this;
  65516. if (this._audioEngine.canUseWebAudio) {
  65517. if (!this._debugCanvas) {
  65518. this._debugCanvas = document.createElement("canvas");
  65519. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65520. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65521. this._debugCanvas.style.position = "absolute";
  65522. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65523. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65524. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65525. document.body.appendChild(this._debugCanvas);
  65526. this._registerFunc = function () {
  65527. _this.drawDebugCanvas();
  65528. };
  65529. this._scene.registerBeforeRender(this._registerFunc);
  65530. }
  65531. if (this._registerFunc && this._debugCanvasContext) {
  65532. var workingArray = this.getByteFrequencyData();
  65533. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65534. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65535. // Draw the frequency domain chart.
  65536. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65537. var value = workingArray[i];
  65538. var percent = value / this.BARGRAPHAMPLITUDE;
  65539. var height = this.DEBUGCANVASSIZE.height * percent;
  65540. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65541. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65542. var hue = i / this.getFrequencyBinCount() * 360;
  65543. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65544. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65545. }
  65546. }
  65547. }
  65548. };
  65549. /**
  65550. * Stops rendering the debug canvas and removes it
  65551. */
  65552. Analyser.prototype.stopDebugCanvas = function () {
  65553. if (this._debugCanvas) {
  65554. if (this._registerFunc) {
  65555. this._scene.unregisterBeforeRender(this._registerFunc);
  65556. this._registerFunc = null;
  65557. }
  65558. document.body.removeChild(this._debugCanvas);
  65559. this._debugCanvas = null;
  65560. this._debugCanvasContext = null;
  65561. }
  65562. };
  65563. /**
  65564. * Connects two audio nodes
  65565. * @param inputAudioNode defines first node to connect
  65566. * @param outputAudioNode defines second node to connect
  65567. */
  65568. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65569. if (this._audioEngine.canUseWebAudio) {
  65570. inputAudioNode.connect(this._webAudioAnalyser);
  65571. this._webAudioAnalyser.connect(outputAudioNode);
  65572. }
  65573. };
  65574. /**
  65575. * Releases all associated resources
  65576. */
  65577. Analyser.prototype.dispose = function () {
  65578. if (this._audioEngine.canUseWebAudio) {
  65579. this._webAudioAnalyser.disconnect();
  65580. }
  65581. };
  65582. return Analyser;
  65583. }());
  65584. BABYLON.Analyser = Analyser;
  65585. })(BABYLON || (BABYLON = {}));
  65586. //# sourceMappingURL=babylon.analyser.js.map
  65587. var BABYLON;
  65588. (function (BABYLON) {
  65589. /**
  65590. * Wraps one or more Sound objects and selects one with random weight for playback.
  65591. */
  65592. var WeightedSound = /** @class */ (function () {
  65593. /**
  65594. * Creates a new WeightedSound from the list of sounds given.
  65595. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65596. * @param sounds Array of Sounds that will be selected from.
  65597. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65598. */
  65599. function WeightedSound(loop, sounds, weights) {
  65600. var _this = this;
  65601. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65602. this.loop = false;
  65603. this._coneInnerAngle = 360;
  65604. this._coneOuterAngle = 360;
  65605. this._volume = 1;
  65606. /** A Sound is currently playing. */
  65607. this.isPlaying = false;
  65608. /** A Sound is currently paused. */
  65609. this.isPaused = false;
  65610. this._sounds = [];
  65611. this._weights = [];
  65612. if (sounds.length !== weights.length) {
  65613. throw new Error('Sounds length does not equal weights length');
  65614. }
  65615. this.loop = loop;
  65616. this._weights = weights;
  65617. // Normalize the weights
  65618. var weightSum = 0;
  65619. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65620. var weight = weights_1[_i];
  65621. weightSum += weight;
  65622. }
  65623. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65624. for (var i = 0; i < this._weights.length; i++) {
  65625. this._weights[i] *= invWeightSum;
  65626. }
  65627. this._sounds = sounds;
  65628. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65629. var sound = _b[_a];
  65630. sound.onEndedObservable.add(function () { _this._onended(); });
  65631. }
  65632. }
  65633. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65634. /**
  65635. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65636. */
  65637. get: function () {
  65638. return this._coneInnerAngle;
  65639. },
  65640. /**
  65641. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65642. */
  65643. set: function (value) {
  65644. if (value !== this._coneInnerAngle) {
  65645. if (this._coneOuterAngle < value) {
  65646. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65647. return;
  65648. }
  65649. this._coneInnerAngle = value;
  65650. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65651. var sound = _a[_i];
  65652. sound.directionalConeInnerAngle = value;
  65653. }
  65654. }
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65660. /**
  65661. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65662. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65663. */
  65664. get: function () {
  65665. return this._coneOuterAngle;
  65666. },
  65667. /**
  65668. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65669. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65670. */
  65671. set: function (value) {
  65672. if (value !== this._coneOuterAngle) {
  65673. if (value < this._coneInnerAngle) {
  65674. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65675. return;
  65676. }
  65677. this._coneOuterAngle = value;
  65678. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65679. var sound = _a[_i];
  65680. sound.directionalConeOuterAngle = value;
  65681. }
  65682. }
  65683. },
  65684. enumerable: true,
  65685. configurable: true
  65686. });
  65687. Object.defineProperty(WeightedSound.prototype, "volume", {
  65688. /**
  65689. * Playback volume.
  65690. */
  65691. get: function () {
  65692. return this._volume;
  65693. },
  65694. /**
  65695. * Playback volume.
  65696. */
  65697. set: function (value) {
  65698. if (value !== this._volume) {
  65699. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65700. var sound = _a[_i];
  65701. sound.setVolume(value);
  65702. }
  65703. }
  65704. },
  65705. enumerable: true,
  65706. configurable: true
  65707. });
  65708. WeightedSound.prototype._onended = function () {
  65709. if (this._currentIndex !== undefined) {
  65710. this._sounds[this._currentIndex].autoplay = false;
  65711. }
  65712. if (this.loop && this.isPlaying) {
  65713. this.play();
  65714. }
  65715. else {
  65716. this.isPlaying = false;
  65717. }
  65718. };
  65719. /**
  65720. * Suspend playback
  65721. */
  65722. WeightedSound.prototype.pause = function () {
  65723. this.isPaused = true;
  65724. if (this._currentIndex !== undefined) {
  65725. this._sounds[this._currentIndex].pause();
  65726. }
  65727. };
  65728. /**
  65729. * Stop playback
  65730. */
  65731. WeightedSound.prototype.stop = function () {
  65732. this.isPlaying = false;
  65733. if (this._currentIndex !== undefined) {
  65734. this._sounds[this._currentIndex].stop();
  65735. }
  65736. };
  65737. /**
  65738. * Start playback.
  65739. * @param startOffset Position the clip head at a specific time in seconds.
  65740. */
  65741. WeightedSound.prototype.play = function (startOffset) {
  65742. if (!this.isPaused) {
  65743. this.stop();
  65744. var randomValue = Math.random();
  65745. var total = 0;
  65746. for (var i = 0; i < this._weights.length; i++) {
  65747. total += this._weights[i];
  65748. if (randomValue <= total) {
  65749. this._currentIndex = i;
  65750. break;
  65751. }
  65752. }
  65753. }
  65754. var sound = this._sounds[this._currentIndex];
  65755. if (sound.isReady()) {
  65756. sound.play(0, this.isPaused ? undefined : startOffset);
  65757. }
  65758. else {
  65759. sound.autoplay = true;
  65760. }
  65761. this.isPlaying = true;
  65762. this.isPaused = false;
  65763. };
  65764. return WeightedSound;
  65765. }());
  65766. BABYLON.WeightedSound = WeightedSound;
  65767. })(BABYLON || (BABYLON = {}));
  65768. //# sourceMappingURL=babylon.weightedsound.js.map
  65769. var BABYLON;
  65770. (function (BABYLON) {
  65771. var CubeTexture = /** @class */ (function (_super) {
  65772. __extends(CubeTexture, _super);
  65773. /**
  65774. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  65775. * as prefiltered data.
  65776. * @param rootUrl defines the url of the texture or the root name of the six images
  65777. * @param scene defines the scene the texture is attached to
  65778. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  65779. * @param noMipmap defines if mipmaps should be created or not
  65780. * @param files defines the six files to load for the different faces
  65781. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  65782. * @param onError defines a callback triggered in case of error during load
  65783. * @param format defines the internal format to use for the texture once loaded
  65784. * @param prefiltered defines whether or not the texture is created from prefiltered data
  65785. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  65786. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65787. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65788. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65789. * @return the cube texture
  65790. */
  65791. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  65792. if (extensions === void 0) { extensions = null; }
  65793. if (noMipmap === void 0) { noMipmap = false; }
  65794. if (files === void 0) { files = null; }
  65795. if (onLoad === void 0) { onLoad = null; }
  65796. if (onError === void 0) { onError = null; }
  65797. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65798. if (prefiltered === void 0) { prefiltered = false; }
  65799. if (forcedExtension === void 0) { forcedExtension = null; }
  65800. if (createPolynomials === void 0) { createPolynomials = false; }
  65801. if (lodScale === void 0) { lodScale = 0.8; }
  65802. if (lodOffset === void 0) { lodOffset = 0; }
  65803. var _this = _super.call(this, scene) || this;
  65804. /**
  65805. * Gets or sets the center of the bounding box associated with the cube texture
  65806. * It must define where the camera used to render the texture was set
  65807. */
  65808. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65809. _this._rotationY = 0;
  65810. /** @hidden */
  65811. _this._prefiltered = false;
  65812. _this.name = rootUrl;
  65813. _this.url = rootUrl;
  65814. _this._noMipmap = noMipmap;
  65815. _this.hasAlpha = false;
  65816. _this._format = format;
  65817. _this.isCube = true;
  65818. _this._textureMatrix = BABYLON.Matrix.Identity();
  65819. _this._createPolynomials = createPolynomials;
  65820. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65821. if (!rootUrl && !files) {
  65822. return _this;
  65823. }
  65824. var lastDot = rootUrl.lastIndexOf(".");
  65825. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  65826. var isDDS = (extension === ".dds");
  65827. var isEnv = (extension === ".env");
  65828. if (isEnv) {
  65829. _this.gammaSpace = false;
  65830. _this._prefiltered = false;
  65831. }
  65832. else {
  65833. _this._prefiltered = prefiltered;
  65834. if (prefiltered) {
  65835. _this.gammaSpace = false;
  65836. }
  65837. }
  65838. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  65839. if (!files) {
  65840. if (!isEnv && !isDDS && !extensions) {
  65841. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  65842. }
  65843. files = [];
  65844. if (extensions) {
  65845. for (var index = 0; index < extensions.length; index++) {
  65846. files.push(rootUrl + extensions[index]);
  65847. }
  65848. }
  65849. }
  65850. _this._files = files;
  65851. if (!_this._texture) {
  65852. if (!scene.useDelayedTextureLoading) {
  65853. if (prefiltered) {
  65854. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  65855. }
  65856. else {
  65857. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  65858. }
  65859. }
  65860. else {
  65861. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65862. }
  65863. }
  65864. else if (onLoad) {
  65865. if (_this._texture.isReady) {
  65866. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  65867. }
  65868. else {
  65869. _this._texture.onLoadedObservable.add(onLoad);
  65870. }
  65871. }
  65872. return _this;
  65873. }
  65874. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  65875. get: function () {
  65876. return this._boundingBoxSize;
  65877. },
  65878. /**
  65879. * Gets or sets the size of the bounding box associated with the cube texture
  65880. * When defined, the cubemap will switch to local mode
  65881. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65882. * @example https://www.babylonjs-playground.com/#RNASML
  65883. */
  65884. set: function (value) {
  65885. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65886. return;
  65887. }
  65888. this._boundingBoxSize = value;
  65889. var scene = this.getScene();
  65890. if (scene) {
  65891. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65892. }
  65893. },
  65894. enumerable: true,
  65895. configurable: true
  65896. });
  65897. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  65898. /**
  65899. * Gets texture matrix rotation angle around Y axis radians.
  65900. */
  65901. get: function () {
  65902. return this._rotationY;
  65903. },
  65904. /**
  65905. * Sets texture matrix rotation angle around Y axis in radians.
  65906. */
  65907. set: function (value) {
  65908. this._rotationY = value;
  65909. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  65910. },
  65911. enumerable: true,
  65912. configurable: true
  65913. });
  65914. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  65915. var rootUrlKey = "";
  65916. files.forEach(function (url) { return rootUrlKey += url; });
  65917. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  65918. };
  65919. /**
  65920. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  65921. * @param url defines the url of the prefiltered texture
  65922. * @param scene defines the scene the texture is attached to
  65923. * @param forcedExtension defines the extension of the file if different from the url
  65924. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65925. * @return the prefiltered texture
  65926. */
  65927. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  65928. if (forcedExtension === void 0) { forcedExtension = null; }
  65929. if (createPolynomials === void 0) { createPolynomials = true; }
  65930. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  65931. };
  65932. // Methods
  65933. CubeTexture.prototype.delayLoad = function () {
  65934. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65935. return;
  65936. }
  65937. var scene = this.getScene();
  65938. if (!scene) {
  65939. return;
  65940. }
  65941. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65942. this._texture = this._getFromCache(this.url, this._noMipmap);
  65943. if (!this._texture) {
  65944. if (this._prefiltered) {
  65945. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  65946. }
  65947. else {
  65948. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  65949. }
  65950. }
  65951. };
  65952. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  65953. return this._textureMatrix;
  65954. };
  65955. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65956. this._textureMatrix = value;
  65957. };
  65958. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65959. var texture = BABYLON.SerializationHelper.Parse(function () {
  65960. var prefiltered = false;
  65961. if (parsedTexture.prefiltered) {
  65962. prefiltered = parsedTexture.prefiltered;
  65963. }
  65964. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  65965. }, parsedTexture, scene);
  65966. // Local Cubemaps
  65967. if (parsedTexture.boundingBoxPosition) {
  65968. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  65969. }
  65970. if (parsedTexture.boundingBoxSize) {
  65971. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  65972. }
  65973. // Animations
  65974. if (parsedTexture.animations) {
  65975. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  65976. var parsedAnimation = parsedTexture.animations[animationIndex];
  65977. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  65978. }
  65979. }
  65980. return texture;
  65981. };
  65982. CubeTexture.prototype.clone = function () {
  65983. var _this = this;
  65984. return BABYLON.SerializationHelper.Clone(function () {
  65985. var scene = _this.getScene();
  65986. if (!scene) {
  65987. return _this;
  65988. }
  65989. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  65990. }, this);
  65991. };
  65992. __decorate([
  65993. BABYLON.serialize("rotationY")
  65994. ], CubeTexture.prototype, "_rotationY", void 0);
  65995. return CubeTexture;
  65996. }(BABYLON.BaseTexture));
  65997. BABYLON.CubeTexture = CubeTexture;
  65998. })(BABYLON || (BABYLON = {}));
  65999. //# sourceMappingURL=babylon.cubeTexture.js.map
  66000. var BABYLON;
  66001. (function (BABYLON) {
  66002. /**
  66003. * Raw cube texture where the raw buffers are passed in
  66004. */
  66005. var RawCubeTexture = /** @class */ (function (_super) {
  66006. __extends(RawCubeTexture, _super);
  66007. /**
  66008. * Creates a cube texture where the raw buffers are passed in.
  66009. * @param scene defines the scene the texture is attached to
  66010. * @param data defines the array of data to use to create each face
  66011. * @param size defines the size of the textures
  66012. * @param format defines the format of the data
  66013. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66014. * @param generateMipMaps defines if the engine should generate the mip levels
  66015. * @param invertY defines if data must be stored with Y axis inverted
  66016. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66017. * @param compression defines the compression used (null by default)
  66018. */
  66019. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66020. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66021. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66022. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66023. if (invertY === void 0) { invertY = false; }
  66024. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66025. if (compression === void 0) { compression = null; }
  66026. var _this = _super.call(this, "", scene) || this;
  66027. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66028. return _this;
  66029. }
  66030. /**
  66031. * Updates the raw cube texture.
  66032. * @param data defines the data to store
  66033. * @param format defines the data format
  66034. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66035. * @param invertY defines if data must be stored with Y axis inverted
  66036. * @param compression defines the compression used (null by default)
  66037. * @param level defines which level of the texture to update
  66038. */
  66039. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66040. if (compression === void 0) { compression = null; }
  66041. if (level === void 0) { level = 0; }
  66042. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66043. };
  66044. /**
  66045. * Updates a raw cube texture with RGBD encoded data.
  66046. * @param data defines the array of data [mipmap][face] to use to create each face
  66047. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66048. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66049. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66050. * @returns a promsie that resolves when the operation is complete
  66051. */
  66052. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66053. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66054. if (lodScale === void 0) { lodScale = 0.8; }
  66055. if (lodOffset === void 0) { lodOffset = 0; }
  66056. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66057. };
  66058. /**
  66059. * Clones the raw cube texture.
  66060. * @return a new cube texture
  66061. */
  66062. RawCubeTexture.prototype.clone = function () {
  66063. var _this = this;
  66064. return BABYLON.SerializationHelper.Clone(function () {
  66065. var scene = _this.getScene();
  66066. var internalTexture = _this._texture;
  66067. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66068. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66069. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66070. }
  66071. return texture;
  66072. }, this);
  66073. };
  66074. /** @hidden */
  66075. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66076. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66077. internalTexture._bufferViewArrayArray = data;
  66078. internalTexture._lodGenerationScale = lodScale;
  66079. internalTexture._lodGenerationOffset = lodOffset;
  66080. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66081. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66082. internalTexture.isReady = true;
  66083. });
  66084. };
  66085. return RawCubeTexture;
  66086. }(BABYLON.CubeTexture));
  66087. BABYLON.RawCubeTexture = RawCubeTexture;
  66088. })(BABYLON || (BABYLON = {}));
  66089. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66090. var BABYLON;
  66091. (function (BABYLON) {
  66092. var RenderTargetTexture = /** @class */ (function (_super) {
  66093. __extends(RenderTargetTexture, _super);
  66094. /**
  66095. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66096. * or used a shadow, depth texture...
  66097. * @param name The friendly name of the texture
  66098. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  66099. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66100. * @param generateMipMaps True if mip maps need to be generated after render.
  66101. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66102. * @param type The type of the buffer in the RTT (int, half float, float...)
  66103. * @param isCube True if a cube texture needs to be created
  66104. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66105. * @param generateDepthBuffer True to generate a depth buffer
  66106. * @param generateStencilBuffer True to generate a stencil buffer
  66107. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66108. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66109. */
  66110. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66111. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66112. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66113. if (isCube === void 0) { isCube = false; }
  66114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66115. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66116. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66117. if (isMulti === void 0) { isMulti = false; }
  66118. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66119. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66120. _this.isCube = isCube;
  66121. _this.renderParticles = true;
  66122. _this.renderSprites = false;
  66123. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66124. _this.ignoreCameraViewport = false;
  66125. // Events
  66126. /**
  66127. * An event triggered when the texture is unbind.
  66128. */
  66129. _this.onBeforeBindObservable = new BABYLON.Observable();
  66130. /**
  66131. * An event triggered when the texture is unbind.
  66132. */
  66133. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66134. /**
  66135. * An event triggered before rendering the texture
  66136. */
  66137. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66138. /**
  66139. * An event triggered after rendering the texture
  66140. */
  66141. _this.onAfterRenderObservable = new BABYLON.Observable();
  66142. /**
  66143. * An event triggered after the texture clear
  66144. */
  66145. _this.onClearObservable = new BABYLON.Observable();
  66146. _this._currentRefreshId = -1;
  66147. _this._refreshRate = 1;
  66148. _this._samples = 1;
  66149. /**
  66150. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66151. * It must define where the camera used to render the texture is set
  66152. */
  66153. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66154. scene = _this.getScene();
  66155. if (!scene) {
  66156. return _this;
  66157. }
  66158. _this.renderList = new Array();
  66159. _this._engine = scene.getEngine();
  66160. _this.name = name;
  66161. _this.isRenderTarget = true;
  66162. _this._initialSizeParameter = size;
  66163. _this._processSizeParameter(size);
  66164. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66165. });
  66166. _this._generateMipMaps = generateMipMaps ? true : false;
  66167. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66168. // Rendering groups
  66169. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66170. _this._renderingManager._useSceneAutoClearSetup = true;
  66171. if (isMulti) {
  66172. return _this;
  66173. }
  66174. _this._renderTargetOptions = {
  66175. generateMipMaps: generateMipMaps,
  66176. type: type,
  66177. format: format,
  66178. samplingMode: samplingMode,
  66179. generateDepthBuffer: generateDepthBuffer,
  66180. generateStencilBuffer: generateStencilBuffer
  66181. };
  66182. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66183. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66184. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66185. }
  66186. if (isCube) {
  66187. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66188. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66189. _this._textureMatrix = BABYLON.Matrix.Identity();
  66190. }
  66191. else {
  66192. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66193. }
  66194. return _this;
  66195. }
  66196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66197. get: function () {
  66198. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66199. },
  66200. enumerable: true,
  66201. configurable: true
  66202. });
  66203. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66204. get: function () {
  66205. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66206. },
  66207. enumerable: true,
  66208. configurable: true
  66209. });
  66210. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66211. get: function () {
  66212. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66213. },
  66214. enumerable: true,
  66215. configurable: true
  66216. });
  66217. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66218. /**
  66219. * Use this list to define the list of mesh you want to render.
  66220. */
  66221. get: function () {
  66222. return this._renderList;
  66223. },
  66224. set: function (value) {
  66225. this._renderList = value;
  66226. if (this._renderList) {
  66227. this._hookArray(this._renderList);
  66228. }
  66229. },
  66230. enumerable: true,
  66231. configurable: true
  66232. });
  66233. RenderTargetTexture.prototype._hookArray = function (array) {
  66234. var _this = this;
  66235. var oldPush = array.push;
  66236. array.push = function () {
  66237. var items = [];
  66238. for (var _i = 0; _i < arguments.length; _i++) {
  66239. items[_i] = arguments[_i];
  66240. }
  66241. var result = oldPush.apply(array, items);
  66242. _this.getScene().meshes.forEach(function (mesh) {
  66243. mesh._markSubMeshesAsLightDirty();
  66244. });
  66245. return result;
  66246. };
  66247. var oldSplice = array.splice;
  66248. array.splice = function (index, deleteCount) {
  66249. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66250. _this.getScene().meshes.forEach(function (mesh) {
  66251. mesh._markSubMeshesAsLightDirty();
  66252. });
  66253. return deleted;
  66254. };
  66255. };
  66256. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66257. set: function (callback) {
  66258. if (this._onAfterUnbindObserver) {
  66259. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66260. }
  66261. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66262. },
  66263. enumerable: true,
  66264. configurable: true
  66265. });
  66266. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66267. set: function (callback) {
  66268. if (this._onBeforeRenderObserver) {
  66269. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66270. }
  66271. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66272. },
  66273. enumerable: true,
  66274. configurable: true
  66275. });
  66276. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66277. set: function (callback) {
  66278. if (this._onAfterRenderObserver) {
  66279. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66280. }
  66281. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66282. },
  66283. enumerable: true,
  66284. configurable: true
  66285. });
  66286. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66287. set: function (callback) {
  66288. if (this._onClearObserver) {
  66289. this.onClearObservable.remove(this._onClearObserver);
  66290. }
  66291. this._onClearObserver = this.onClearObservable.add(callback);
  66292. },
  66293. enumerable: true,
  66294. configurable: true
  66295. });
  66296. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66297. get: function () {
  66298. return this._renderTargetOptions;
  66299. },
  66300. enumerable: true,
  66301. configurable: true
  66302. });
  66303. RenderTargetTexture.prototype._onRatioRescale = function () {
  66304. if (this._sizeRatio) {
  66305. this.resize(this._initialSizeParameter);
  66306. }
  66307. };
  66308. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66309. get: function () {
  66310. return this._boundingBoxSize;
  66311. },
  66312. /**
  66313. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66314. * When defined, the cubemap will switch to local mode
  66315. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66316. * @example https://www.babylonjs-playground.com/#RNASML
  66317. */
  66318. set: function (value) {
  66319. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66320. return;
  66321. }
  66322. this._boundingBoxSize = value;
  66323. var scene = this.getScene();
  66324. if (scene) {
  66325. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66326. }
  66327. },
  66328. enumerable: true,
  66329. configurable: true
  66330. });
  66331. /**
  66332. * Creates a depth stencil texture.
  66333. * This is only available in WebGL 2 or with the depth texture extension available.
  66334. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66335. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66336. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66337. */
  66338. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66339. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66340. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66341. if (generateStencil === void 0) { generateStencil = false; }
  66342. if (!this.getScene()) {
  66343. return;
  66344. }
  66345. var engine = this.getScene().getEngine();
  66346. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66347. bilinearFiltering: bilinearFiltering,
  66348. comparisonFunction: comparisonFunction,
  66349. generateStencil: generateStencil,
  66350. isCube: this.isCube
  66351. });
  66352. engine.setFrameBufferDepthStencilTexture(this);
  66353. };
  66354. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66355. if (size.ratio) {
  66356. this._sizeRatio = size.ratio;
  66357. this._size = {
  66358. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66359. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66360. };
  66361. }
  66362. else {
  66363. this._size = size;
  66364. }
  66365. };
  66366. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66367. get: function () {
  66368. return this._samples;
  66369. },
  66370. set: function (value) {
  66371. if (this._samples === value) {
  66372. return;
  66373. }
  66374. var scene = this.getScene();
  66375. if (!scene) {
  66376. return;
  66377. }
  66378. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66379. },
  66380. enumerable: true,
  66381. configurable: true
  66382. });
  66383. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66384. this._currentRefreshId = -1;
  66385. };
  66386. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66387. get: function () {
  66388. return this._refreshRate;
  66389. },
  66390. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66391. set: function (value) {
  66392. this._refreshRate = value;
  66393. this.resetRefreshCounter();
  66394. },
  66395. enumerable: true,
  66396. configurable: true
  66397. });
  66398. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66399. if (!this._postProcessManager) {
  66400. var scene = this.getScene();
  66401. if (!scene) {
  66402. return;
  66403. }
  66404. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66405. this._postProcesses = new Array();
  66406. }
  66407. this._postProcesses.push(postProcess);
  66408. this._postProcesses[0].autoClear = false;
  66409. };
  66410. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66411. if (!this._postProcesses) {
  66412. return;
  66413. }
  66414. if (dispose) {
  66415. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66416. var postProcess = _a[_i];
  66417. postProcess.dispose();
  66418. }
  66419. }
  66420. this._postProcesses = [];
  66421. };
  66422. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66423. if (!this._postProcesses) {
  66424. return;
  66425. }
  66426. var index = this._postProcesses.indexOf(postProcess);
  66427. if (index === -1) {
  66428. return;
  66429. }
  66430. this._postProcesses.splice(index, 1);
  66431. if (this._postProcesses.length > 0) {
  66432. this._postProcesses[0].autoClear = false;
  66433. }
  66434. };
  66435. /** @hidden */
  66436. RenderTargetTexture.prototype._shouldRender = function () {
  66437. if (this._currentRefreshId === -1) { // At least render once
  66438. this._currentRefreshId = 1;
  66439. return true;
  66440. }
  66441. if (this.refreshRate === this._currentRefreshId) {
  66442. this._currentRefreshId = 1;
  66443. return true;
  66444. }
  66445. this._currentRefreshId++;
  66446. return false;
  66447. };
  66448. RenderTargetTexture.prototype.getRenderSize = function () {
  66449. if (this._size.width) {
  66450. return this._size.width;
  66451. }
  66452. return this._size;
  66453. };
  66454. RenderTargetTexture.prototype.getRenderWidth = function () {
  66455. if (this._size.width) {
  66456. return this._size.width;
  66457. }
  66458. return this._size;
  66459. };
  66460. RenderTargetTexture.prototype.getRenderHeight = function () {
  66461. if (this._size.width) {
  66462. return this._size.height;
  66463. }
  66464. return this._size;
  66465. };
  66466. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66467. get: function () {
  66468. return true;
  66469. },
  66470. enumerable: true,
  66471. configurable: true
  66472. });
  66473. RenderTargetTexture.prototype.scale = function (ratio) {
  66474. var newSize = this.getRenderSize() * ratio;
  66475. this.resize(newSize);
  66476. };
  66477. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66478. if (this.isCube) {
  66479. return this._textureMatrix;
  66480. }
  66481. return _super.prototype.getReflectionTextureMatrix.call(this);
  66482. };
  66483. RenderTargetTexture.prototype.resize = function (size) {
  66484. this.releaseInternalTexture();
  66485. var scene = this.getScene();
  66486. if (!scene) {
  66487. return;
  66488. }
  66489. this._processSizeParameter(size);
  66490. if (this.isCube) {
  66491. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66492. }
  66493. else {
  66494. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66495. }
  66496. };
  66497. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66498. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66499. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66500. var scene = this.getScene();
  66501. if (!scene) {
  66502. return;
  66503. }
  66504. var engine = scene.getEngine();
  66505. if (this.useCameraPostProcesses !== undefined) {
  66506. useCameraPostProcess = this.useCameraPostProcesses;
  66507. }
  66508. if (this._waitingRenderList) {
  66509. this.renderList = [];
  66510. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66511. var id = this._waitingRenderList[index];
  66512. var mesh_1 = scene.getMeshByID(id);
  66513. if (mesh_1) {
  66514. this.renderList.push(mesh_1);
  66515. }
  66516. }
  66517. delete this._waitingRenderList;
  66518. }
  66519. // Is predicate defined?
  66520. if (this.renderListPredicate) {
  66521. if (this.renderList) {
  66522. this.renderList.splice(0); // Clear previous renderList
  66523. }
  66524. else {
  66525. this.renderList = [];
  66526. }
  66527. var scene = this.getScene();
  66528. if (!scene) {
  66529. return;
  66530. }
  66531. var sceneMeshes = scene.meshes;
  66532. for (var index = 0; index < sceneMeshes.length; index++) {
  66533. var mesh = sceneMeshes[index];
  66534. if (this.renderListPredicate(mesh)) {
  66535. this.renderList.push(mesh);
  66536. }
  66537. }
  66538. }
  66539. this.onBeforeBindObservable.notifyObservers(this);
  66540. // Set custom projection.
  66541. // Needs to be before binding to prevent changing the aspect ratio.
  66542. var camera;
  66543. if (this.activeCamera) {
  66544. camera = this.activeCamera;
  66545. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66546. if (this.activeCamera !== scene.activeCamera) {
  66547. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66548. }
  66549. }
  66550. else {
  66551. camera = scene.activeCamera;
  66552. if (camera) {
  66553. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66554. }
  66555. }
  66556. // Prepare renderingManager
  66557. this._renderingManager.reset();
  66558. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66559. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66560. var sceneRenderId = scene.getRenderId();
  66561. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66562. var mesh = currentRenderList[meshIndex];
  66563. if (mesh) {
  66564. if (!mesh.isReady(this.refreshRate === 0)) {
  66565. this.resetRefreshCounter();
  66566. continue;
  66567. }
  66568. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66569. var isMasked = void 0;
  66570. if (!this.renderList && camera) {
  66571. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66572. }
  66573. else {
  66574. isMasked = false;
  66575. }
  66576. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66577. mesh._activate(sceneRenderId);
  66578. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66579. var subMesh = mesh.subMeshes[subIndex];
  66580. scene._activeIndices.addCount(subMesh.indexCount, false);
  66581. this._renderingManager.dispatch(subMesh, mesh);
  66582. }
  66583. }
  66584. }
  66585. }
  66586. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66587. var particleSystem = scene.particleSystems[particleIndex];
  66588. var emitter = particleSystem.emitter;
  66589. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66590. continue;
  66591. }
  66592. if (currentRenderList.indexOf(emitter) >= 0) {
  66593. this._renderingManager.dispatchParticles(particleSystem);
  66594. }
  66595. }
  66596. if (this.isCube) {
  66597. for (var face = 0; face < 6; face++) {
  66598. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66599. scene.incrementRenderId();
  66600. scene.resetCachedMaterial();
  66601. }
  66602. }
  66603. else {
  66604. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66605. }
  66606. this.onAfterUnbindObservable.notifyObservers(this);
  66607. if (scene.activeCamera) {
  66608. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66609. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66610. }
  66611. engine.setViewport(scene.activeCamera.viewport);
  66612. }
  66613. scene.resetCachedMaterial();
  66614. };
  66615. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66616. var minimum = 128;
  66617. var x = renderDimension * scale;
  66618. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66619. // Ensure we don't exceed the render dimension (while staying POT)
  66620. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66621. };
  66622. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66623. var _this = this;
  66624. if (!this._texture) {
  66625. return;
  66626. }
  66627. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66628. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66629. });
  66630. };
  66631. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66632. var scene = this.getScene();
  66633. if (!scene) {
  66634. return;
  66635. }
  66636. var engine = scene.getEngine();
  66637. if (!this._texture) {
  66638. return;
  66639. }
  66640. // Bind
  66641. if (this._postProcessManager) {
  66642. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66643. }
  66644. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66645. if (this._texture) {
  66646. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66647. }
  66648. }
  66649. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66650. // Clear
  66651. if (this.onClearObservable.hasObservers()) {
  66652. this.onClearObservable.notifyObservers(engine);
  66653. }
  66654. else {
  66655. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66656. }
  66657. if (!this._doNotChangeAspectRatio) {
  66658. scene.updateTransformMatrix(true);
  66659. }
  66660. // Render
  66661. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66662. if (this._postProcessManager) {
  66663. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66664. }
  66665. else if (useCameraPostProcess) {
  66666. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66667. }
  66668. if (!this._doNotChangeAspectRatio) {
  66669. scene.updateTransformMatrix(true);
  66670. }
  66671. // Dump ?
  66672. if (dumpForDebug) {
  66673. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66674. }
  66675. // Unbind
  66676. if (!this.isCube || faceIndex === 5) {
  66677. if (this.isCube) {
  66678. if (faceIndex === 5) {
  66679. engine.generateMipMapsForCubemap(this._texture);
  66680. }
  66681. }
  66682. this.unbindFrameBuffer(engine, faceIndex);
  66683. }
  66684. else {
  66685. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66686. }
  66687. };
  66688. /**
  66689. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66690. * This allowed control for front to back rendering or reversly depending of the special needs.
  66691. *
  66692. * @param renderingGroupId The rendering group id corresponding to its index
  66693. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66694. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66695. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66696. */
  66697. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66698. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66699. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66700. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66701. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66702. };
  66703. /**
  66704. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66705. *
  66706. * @param renderingGroupId The rendering group id corresponding to its index
  66707. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66708. */
  66709. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66710. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66711. this._renderingManager._useSceneAutoClearSetup = false;
  66712. };
  66713. RenderTargetTexture.prototype.clone = function () {
  66714. var textureSize = this.getSize();
  66715. 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);
  66716. // Base texture
  66717. newTexture.hasAlpha = this.hasAlpha;
  66718. newTexture.level = this.level;
  66719. // RenderTarget Texture
  66720. newTexture.coordinatesMode = this.coordinatesMode;
  66721. if (this.renderList) {
  66722. newTexture.renderList = this.renderList.slice(0);
  66723. }
  66724. return newTexture;
  66725. };
  66726. RenderTargetTexture.prototype.serialize = function () {
  66727. if (!this.name) {
  66728. return null;
  66729. }
  66730. var serializationObject = _super.prototype.serialize.call(this);
  66731. serializationObject.renderTargetSize = this.getRenderSize();
  66732. serializationObject.renderList = [];
  66733. if (this.renderList) {
  66734. for (var index = 0; index < this.renderList.length; index++) {
  66735. serializationObject.renderList.push(this.renderList[index].id);
  66736. }
  66737. }
  66738. return serializationObject;
  66739. };
  66740. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66741. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66742. var objBuffer = this.getInternalTexture();
  66743. var scene = this.getScene();
  66744. if (objBuffer && scene) {
  66745. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66746. }
  66747. };
  66748. RenderTargetTexture.prototype.dispose = function () {
  66749. if (this._postProcessManager) {
  66750. this._postProcessManager.dispose();
  66751. this._postProcessManager = null;
  66752. }
  66753. this.clearPostProcesses(true);
  66754. if (this._resizeObserver) {
  66755. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66756. this._resizeObserver = null;
  66757. }
  66758. this.renderList = null;
  66759. // Remove from custom render targets
  66760. var scene = this.getScene();
  66761. if (!scene) {
  66762. return;
  66763. }
  66764. var index = scene.customRenderTargets.indexOf(this);
  66765. if (index >= 0) {
  66766. scene.customRenderTargets.splice(index, 1);
  66767. }
  66768. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66769. var camera = _a[_i];
  66770. index = camera.customRenderTargets.indexOf(this);
  66771. if (index >= 0) {
  66772. camera.customRenderTargets.splice(index, 1);
  66773. }
  66774. }
  66775. _super.prototype.dispose.call(this);
  66776. };
  66777. /** @hidden */
  66778. RenderTargetTexture.prototype._rebuild = function () {
  66779. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66780. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66781. }
  66782. if (this._postProcessManager) {
  66783. this._postProcessManager._rebuild();
  66784. }
  66785. };
  66786. /**
  66787. * Clear the info related to rendering groups preventing retention point in material dispose.
  66788. */
  66789. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  66790. if (this._renderingManager) {
  66791. this._renderingManager.freeRenderingGroups();
  66792. }
  66793. };
  66794. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  66795. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  66796. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  66797. return RenderTargetTexture;
  66798. }(BABYLON.Texture));
  66799. BABYLON.RenderTargetTexture = RenderTargetTexture;
  66800. })(BABYLON || (BABYLON = {}));
  66801. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  66802. var BABYLON;
  66803. (function (BABYLON) {
  66804. ;
  66805. var MultiRenderTarget = /** @class */ (function (_super) {
  66806. __extends(MultiRenderTarget, _super);
  66807. function MultiRenderTarget(name, size, count, scene, options) {
  66808. var _this = this;
  66809. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  66810. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  66811. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  66812. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  66813. _this._engine = scene.getEngine();
  66814. if (!_this.isSupported) {
  66815. _this.dispose();
  66816. return;
  66817. }
  66818. var types = [];
  66819. var samplingModes = [];
  66820. for (var i = 0; i < count; i++) {
  66821. if (options && options.types && options.types[i] !== undefined) {
  66822. types.push(options.types[i]);
  66823. }
  66824. else {
  66825. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66826. }
  66827. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  66828. samplingModes.push(options.samplingModes[i]);
  66829. }
  66830. else {
  66831. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66832. }
  66833. }
  66834. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  66835. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  66836. _this._size = size;
  66837. _this._multiRenderTargetOptions = {
  66838. samplingModes: samplingModes,
  66839. generateMipMaps: generateMipMaps,
  66840. generateDepthBuffer: generateDepthBuffer,
  66841. generateStencilBuffer: generateStencilBuffer,
  66842. generateDepthTexture: generateDepthTexture,
  66843. types: types,
  66844. textureCount: count
  66845. };
  66846. _this._createInternalTextures();
  66847. _this._createTextures();
  66848. return _this;
  66849. }
  66850. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  66851. get: function () {
  66852. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  66853. },
  66854. enumerable: true,
  66855. configurable: true
  66856. });
  66857. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  66858. get: function () {
  66859. return this._textures;
  66860. },
  66861. enumerable: true,
  66862. configurable: true
  66863. });
  66864. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  66865. get: function () {
  66866. return this._textures[this._textures.length - 1];
  66867. },
  66868. enumerable: true,
  66869. configurable: true
  66870. });
  66871. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  66872. set: function (wrap) {
  66873. if (this._textures) {
  66874. for (var i = 0; i < this._textures.length; i++) {
  66875. this._textures[i].wrapU = wrap;
  66876. }
  66877. }
  66878. },
  66879. enumerable: true,
  66880. configurable: true
  66881. });
  66882. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  66883. set: function (wrap) {
  66884. if (this._textures) {
  66885. for (var i = 0; i < this._textures.length; i++) {
  66886. this._textures[i].wrapV = wrap;
  66887. }
  66888. }
  66889. },
  66890. enumerable: true,
  66891. configurable: true
  66892. });
  66893. /** @hidden */
  66894. MultiRenderTarget.prototype._rebuild = function () {
  66895. this.releaseInternalTextures();
  66896. this._createInternalTextures();
  66897. for (var i = 0; i < this._internalTextures.length; i++) {
  66898. var texture = this._textures[i];
  66899. texture._texture = this._internalTextures[i];
  66900. }
  66901. // Keeps references to frame buffer and stencil/depth buffer
  66902. this._texture = this._internalTextures[0];
  66903. };
  66904. MultiRenderTarget.prototype._createInternalTextures = function () {
  66905. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  66906. };
  66907. MultiRenderTarget.prototype._createTextures = function () {
  66908. this._textures = [];
  66909. for (var i = 0; i < this._internalTextures.length; i++) {
  66910. var texture = new BABYLON.Texture(null, this.getScene());
  66911. texture._texture = this._internalTextures[i];
  66912. this._textures.push(texture);
  66913. }
  66914. // Keeps references to frame buffer and stencil/depth buffer
  66915. this._texture = this._internalTextures[0];
  66916. };
  66917. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  66918. get: function () {
  66919. return this._samples;
  66920. },
  66921. set: function (value) {
  66922. if (this._samples === value) {
  66923. return;
  66924. }
  66925. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  66926. },
  66927. enumerable: true,
  66928. configurable: true
  66929. });
  66930. MultiRenderTarget.prototype.resize = function (size) {
  66931. this.releaseInternalTextures();
  66932. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  66933. this._createInternalTextures();
  66934. };
  66935. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66936. var _this = this;
  66937. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  66938. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66939. });
  66940. };
  66941. MultiRenderTarget.prototype.dispose = function () {
  66942. this.releaseInternalTextures();
  66943. _super.prototype.dispose.call(this);
  66944. };
  66945. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  66946. if (!this._internalTextures) {
  66947. return;
  66948. }
  66949. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  66950. if (this._internalTextures[i] !== undefined) {
  66951. this._internalTextures[i].dispose();
  66952. this._internalTextures.splice(i, 1);
  66953. }
  66954. }
  66955. };
  66956. return MultiRenderTarget;
  66957. }(BABYLON.RenderTargetTexture));
  66958. BABYLON.MultiRenderTarget = MultiRenderTarget;
  66959. })(BABYLON || (BABYLON = {}));
  66960. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  66961. var BABYLON;
  66962. (function (BABYLON) {
  66963. var MirrorTexture = /** @class */ (function (_super) {
  66964. __extends(MirrorTexture, _super);
  66965. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  66966. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66968. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66969. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  66970. _this.scene = scene;
  66971. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  66972. _this._transformMatrix = BABYLON.Matrix.Zero();
  66973. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  66974. _this._adaptiveBlurKernel = 0;
  66975. _this._blurKernelX = 0;
  66976. _this._blurKernelY = 0;
  66977. _this._blurRatio = 1.0;
  66978. _this.ignoreCameraViewport = true;
  66979. _this._updateGammaSpace();
  66980. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  66981. _this._updateGammaSpace;
  66982. });
  66983. _this.onBeforeRenderObservable.add(function () {
  66984. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  66985. _this._savedViewMatrix = scene.getViewMatrix();
  66986. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  66987. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  66988. scene.clipPlane = _this.mirrorPlane;
  66989. scene.getEngine().cullBackFaces = false;
  66990. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  66991. });
  66992. _this.onAfterRenderObservable.add(function () {
  66993. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  66994. scene.getEngine().cullBackFaces = true;
  66995. scene._mirroredCameraPosition = null;
  66996. delete scene.clipPlane;
  66997. });
  66998. return _this;
  66999. }
  67000. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67001. get: function () {
  67002. return this._blurRatio;
  67003. },
  67004. set: function (value) {
  67005. if (this._blurRatio === value) {
  67006. return;
  67007. }
  67008. this._blurRatio = value;
  67009. this._preparePostProcesses();
  67010. },
  67011. enumerable: true,
  67012. configurable: true
  67013. });
  67014. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67015. set: function (value) {
  67016. this._adaptiveBlurKernel = value;
  67017. this._autoComputeBlurKernel();
  67018. },
  67019. enumerable: true,
  67020. configurable: true
  67021. });
  67022. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67023. set: function (value) {
  67024. this.blurKernelX = value;
  67025. this.blurKernelY = value;
  67026. },
  67027. enumerable: true,
  67028. configurable: true
  67029. });
  67030. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67031. get: function () {
  67032. return this._blurKernelX;
  67033. },
  67034. set: function (value) {
  67035. if (this._blurKernelX === value) {
  67036. return;
  67037. }
  67038. this._blurKernelX = value;
  67039. this._preparePostProcesses();
  67040. },
  67041. enumerable: true,
  67042. configurable: true
  67043. });
  67044. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67045. get: function () {
  67046. return this._blurKernelY;
  67047. },
  67048. set: function (value) {
  67049. if (this._blurKernelY === value) {
  67050. return;
  67051. }
  67052. this._blurKernelY = value;
  67053. this._preparePostProcesses();
  67054. },
  67055. enumerable: true,
  67056. configurable: true
  67057. });
  67058. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67059. var engine = this.getScene().getEngine();
  67060. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67061. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67062. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67063. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67064. };
  67065. MirrorTexture.prototype._onRatioRescale = function () {
  67066. if (this._sizeRatio) {
  67067. this.resize(this._initialSizeParameter);
  67068. if (!this._adaptiveBlurKernel) {
  67069. this._preparePostProcesses();
  67070. }
  67071. }
  67072. if (this._adaptiveBlurKernel) {
  67073. this._autoComputeBlurKernel();
  67074. }
  67075. };
  67076. MirrorTexture.prototype._updateGammaSpace = function () {
  67077. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67078. };
  67079. MirrorTexture.prototype._preparePostProcesses = function () {
  67080. this.clearPostProcesses(true);
  67081. if (this._blurKernelX && this._blurKernelY) {
  67082. var engine = this.getScene().getEngine();
  67083. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67084. 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);
  67085. this._blurX.autoClear = false;
  67086. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67087. this._blurX.inputTexture = this._texture;
  67088. }
  67089. else {
  67090. this._blurX.alwaysForcePOT = true;
  67091. }
  67092. 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);
  67093. this._blurY.autoClear = false;
  67094. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67095. this.addPostProcess(this._blurX);
  67096. this.addPostProcess(this._blurY);
  67097. }
  67098. else {
  67099. if (this._blurY) {
  67100. this.removePostProcess(this._blurY);
  67101. this._blurY.dispose();
  67102. this._blurY = null;
  67103. }
  67104. if (this._blurX) {
  67105. this.removePostProcess(this._blurX);
  67106. this._blurX.dispose();
  67107. this._blurX = null;
  67108. }
  67109. }
  67110. };
  67111. MirrorTexture.prototype.clone = function () {
  67112. var scene = this.getScene();
  67113. if (!scene) {
  67114. return this;
  67115. }
  67116. var textureSize = this.getSize();
  67117. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67118. // Base texture
  67119. newTexture.hasAlpha = this.hasAlpha;
  67120. newTexture.level = this.level;
  67121. // Mirror Texture
  67122. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67123. if (this.renderList) {
  67124. newTexture.renderList = this.renderList.slice(0);
  67125. }
  67126. return newTexture;
  67127. };
  67128. MirrorTexture.prototype.serialize = function () {
  67129. if (!this.name) {
  67130. return null;
  67131. }
  67132. var serializationObject = _super.prototype.serialize.call(this);
  67133. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67134. return serializationObject;
  67135. };
  67136. MirrorTexture.prototype.dispose = function () {
  67137. _super.prototype.dispose.call(this);
  67138. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67139. };
  67140. return MirrorTexture;
  67141. }(BABYLON.RenderTargetTexture));
  67142. BABYLON.MirrorTexture = MirrorTexture;
  67143. })(BABYLON || (BABYLON = {}));
  67144. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67145. var BABYLON;
  67146. (function (BABYLON) {
  67147. /**
  67148. * Creates a refraction texture used by refraction channel of the standard material.
  67149. * @param name the texture name
  67150. * @param size size of the underlying texture
  67151. * @param scene root scene
  67152. */
  67153. var RefractionTexture = /** @class */ (function (_super) {
  67154. __extends(RefractionTexture, _super);
  67155. function RefractionTexture(name, size, scene, generateMipMaps) {
  67156. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67157. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67158. _this.depth = 2.0;
  67159. _this.onBeforeRenderObservable.add(function () {
  67160. scene.clipPlane = _this.refractionPlane;
  67161. });
  67162. _this.onAfterRenderObservable.add(function () {
  67163. delete scene.clipPlane;
  67164. });
  67165. return _this;
  67166. }
  67167. RefractionTexture.prototype.clone = function () {
  67168. var scene = this.getScene();
  67169. if (!scene) {
  67170. return this;
  67171. }
  67172. var textureSize = this.getSize();
  67173. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67174. // Base texture
  67175. newTexture.hasAlpha = this.hasAlpha;
  67176. newTexture.level = this.level;
  67177. // Refraction Texture
  67178. newTexture.refractionPlane = this.refractionPlane.clone();
  67179. if (this.renderList) {
  67180. newTexture.renderList = this.renderList.slice(0);
  67181. }
  67182. newTexture.depth = this.depth;
  67183. return newTexture;
  67184. };
  67185. RefractionTexture.prototype.serialize = function () {
  67186. if (!this.name) {
  67187. return null;
  67188. }
  67189. var serializationObject = _super.prototype.serialize.call(this);
  67190. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67191. serializationObject.depth = this.depth;
  67192. return serializationObject;
  67193. };
  67194. return RefractionTexture;
  67195. }(BABYLON.RenderTargetTexture));
  67196. BABYLON.RefractionTexture = RefractionTexture;
  67197. })(BABYLON || (BABYLON = {}));
  67198. //# sourceMappingURL=babylon.refractionTexture.js.map
  67199. var BABYLON;
  67200. (function (BABYLON) {
  67201. /**
  67202. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67203. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67204. */
  67205. var DynamicTexture = /** @class */ (function (_super) {
  67206. __extends(DynamicTexture, _super);
  67207. /**
  67208. * Creates a {BABYLON.DynamicTexture}
  67209. * @param name defines the name of the texture
  67210. * @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
  67211. * @param scene defines the scene where you want the texture
  67212. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67213. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67214. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67215. */
  67216. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67217. if (scene === void 0) { scene = null; }
  67218. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67219. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67220. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67221. _this.name = name;
  67222. _this._engine = _this.getScene().getEngine();
  67223. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67224. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67225. _this._generateMipMaps = generateMipMaps;
  67226. if (options.getContext) {
  67227. _this._canvas = options;
  67228. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67229. }
  67230. else {
  67231. _this._canvas = document.createElement("canvas");
  67232. if (options.width || options.width === 0) {
  67233. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67234. }
  67235. else {
  67236. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67237. }
  67238. }
  67239. var textureSize = _this.getSize();
  67240. _this._canvas.width = textureSize.width;
  67241. _this._canvas.height = textureSize.height;
  67242. _this._context = _this._canvas.getContext("2d");
  67243. return _this;
  67244. }
  67245. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67246. /**
  67247. * Gets the current state of canRescale
  67248. */
  67249. get: function () {
  67250. return true;
  67251. },
  67252. enumerable: true,
  67253. configurable: true
  67254. });
  67255. DynamicTexture.prototype._recreate = function (textureSize) {
  67256. this._canvas.width = textureSize.width;
  67257. this._canvas.height = textureSize.height;
  67258. this.releaseInternalTexture();
  67259. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67260. };
  67261. /**
  67262. * Scales the texture
  67263. * @param ratio the scale factor to apply to both width and height
  67264. */
  67265. DynamicTexture.prototype.scale = function (ratio) {
  67266. var textureSize = this.getSize();
  67267. textureSize.width *= ratio;
  67268. textureSize.height *= ratio;
  67269. this._recreate(textureSize);
  67270. };
  67271. /**
  67272. * Resizes the texture
  67273. * @param width the new width
  67274. * @param height the new height
  67275. */
  67276. DynamicTexture.prototype.scaleTo = function (width, height) {
  67277. var textureSize = this.getSize();
  67278. textureSize.width = width;
  67279. textureSize.height = height;
  67280. this._recreate(textureSize);
  67281. };
  67282. /**
  67283. * Gets the context of the canvas used by the texture
  67284. * @returns the canvas context of the dynamic texture
  67285. */
  67286. DynamicTexture.prototype.getContext = function () {
  67287. return this._context;
  67288. };
  67289. /**
  67290. * Clears the texture
  67291. */
  67292. DynamicTexture.prototype.clear = function () {
  67293. var size = this.getSize();
  67294. this._context.fillRect(0, 0, size.width, size.height);
  67295. };
  67296. /**
  67297. * Updates the texture
  67298. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67299. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67300. */
  67301. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67302. if (premulAlpha === void 0) { premulAlpha = false; }
  67303. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67304. };
  67305. /**
  67306. * Draws text onto the texture
  67307. * @param text defines the text to be drawn
  67308. * @param x defines the placement of the text from the left
  67309. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67310. * @param font defines the font to be used with font-style, font-size, font-name
  67311. * @param color defines the color used for the text
  67312. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67313. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67314. * @param update defines whether texture is immediately update (default is true)
  67315. */
  67316. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67317. if (update === void 0) { update = true; }
  67318. var size = this.getSize();
  67319. if (clearColor) {
  67320. this._context.fillStyle = clearColor;
  67321. this._context.fillRect(0, 0, size.width, size.height);
  67322. }
  67323. this._context.font = font;
  67324. if (x === null || x === undefined) {
  67325. var textSize = this._context.measureText(text);
  67326. x = (size.width - textSize.width) / 2;
  67327. }
  67328. if (y === null || y === undefined) {
  67329. var fontSize = parseInt((font.replace(/\D/g, '')));
  67330. y = (size.height / 2) + (fontSize / 3.65);
  67331. }
  67332. this._context.fillStyle = color;
  67333. this._context.fillText(text, x, y);
  67334. if (update) {
  67335. this.update(invertY);
  67336. }
  67337. };
  67338. /**
  67339. * Clones the texture
  67340. * @returns the clone of the texture.
  67341. */
  67342. DynamicTexture.prototype.clone = function () {
  67343. var scene = this.getScene();
  67344. if (!scene) {
  67345. return this;
  67346. }
  67347. var textureSize = this.getSize();
  67348. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67349. // Base texture
  67350. newTexture.hasAlpha = this.hasAlpha;
  67351. newTexture.level = this.level;
  67352. // Dynamic Texture
  67353. newTexture.wrapU = this.wrapU;
  67354. newTexture.wrapV = this.wrapV;
  67355. return newTexture;
  67356. };
  67357. /**
  67358. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67359. * @returns a serialized dynamic texture object
  67360. */
  67361. DynamicTexture.prototype.serialize = function () {
  67362. var scene = this.getScene();
  67363. if (scene && !scene.isReady()) {
  67364. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67365. }
  67366. var serializationObject = _super.prototype.serialize.call(this);
  67367. serializationObject.base64String = this._canvas.toDataURL();
  67368. serializationObject.invertY = this._invertY;
  67369. serializationObject.samplingMode = this.samplingMode;
  67370. return serializationObject;
  67371. };
  67372. /** @hidden */
  67373. DynamicTexture.prototype._rebuild = function () {
  67374. this.update();
  67375. };
  67376. return DynamicTexture;
  67377. }(BABYLON.Texture));
  67378. BABYLON.DynamicTexture = DynamicTexture;
  67379. })(BABYLON || (BABYLON = {}));
  67380. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67381. var BABYLON;
  67382. (function (BABYLON) {
  67383. var VideoTexture = /** @class */ (function (_super) {
  67384. __extends(VideoTexture, _super);
  67385. /**
  67386. * Creates a video texture.
  67387. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67388. * @param {string | null} name optional name, will detect from video source, if not defined
  67389. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67390. * @param {BABYLON.Scene} scene is obviously the current scene.
  67391. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67392. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67393. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67394. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67395. */
  67396. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67397. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67398. if (invertY === void 0) { invertY = false; }
  67399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67400. if (settings === void 0) { settings = {
  67401. autoPlay: true,
  67402. loop: true,
  67403. autoUpdateTexture: true,
  67404. }; }
  67405. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67406. _this._onUserActionRequestedObservable = null;
  67407. _this._stillImageCaptured = false;
  67408. _this._poster = false;
  67409. _this._createInternalTexture = function () {
  67410. if (_this._texture != null) {
  67411. if (_this._poster) {
  67412. _this._texture.dispose();
  67413. _this._poster = false;
  67414. }
  67415. else {
  67416. return;
  67417. }
  67418. }
  67419. if (!_this._engine.needPOTTextures ||
  67420. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67421. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67422. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67423. }
  67424. else {
  67425. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67426. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67427. _this._generateMipMaps = false;
  67428. }
  67429. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67430. if (!_this.video.autoplay) {
  67431. var oldHandler_1 = _this.video.onplaying;
  67432. var error_1 = false;
  67433. _this.video.onplaying = function () {
  67434. _this.video.onplaying = oldHandler_1;
  67435. _this._texture.isReady = true;
  67436. _this._updateInternalTexture();
  67437. if (!error_1) {
  67438. _this.video.pause();
  67439. }
  67440. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67441. _this.onLoadObservable.notifyObservers(_this);
  67442. }
  67443. };
  67444. var playing = _this.video.play();
  67445. if (playing) {
  67446. playing.then(function () {
  67447. // Everything is good.
  67448. })
  67449. .catch(function () {
  67450. error_1 = true;
  67451. // On Chrome for instance, new policies might prevent playing without user interaction.
  67452. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67453. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67454. }
  67455. });
  67456. }
  67457. else {
  67458. _this.video.onplaying = oldHandler_1;
  67459. _this._texture.isReady = true;
  67460. _this._updateInternalTexture();
  67461. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67462. _this.onLoadObservable.notifyObservers(_this);
  67463. }
  67464. }
  67465. }
  67466. else {
  67467. _this._texture.isReady = true;
  67468. _this._updateInternalTexture();
  67469. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67470. _this.onLoadObservable.notifyObservers(_this);
  67471. }
  67472. }
  67473. };
  67474. _this.reset = function () {
  67475. if (_this._texture == null) {
  67476. return;
  67477. }
  67478. if (!_this._poster) {
  67479. _this._texture.dispose();
  67480. _this._texture = null;
  67481. }
  67482. };
  67483. _this._updateInternalTexture = function (e) {
  67484. if (_this._texture == null || !_this._texture.isReady) {
  67485. return;
  67486. }
  67487. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67488. return;
  67489. }
  67490. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67491. };
  67492. _this._engine = _this.getScene().getEngine();
  67493. _this._generateMipMaps = generateMipMaps;
  67494. _this._samplingMode = samplingMode;
  67495. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67496. _this.name = name || _this._getName(src);
  67497. _this.video = _this._getVideo(src);
  67498. if (settings.poster) {
  67499. _this.video.poster = settings.poster;
  67500. }
  67501. if (settings.autoPlay !== undefined) {
  67502. _this.video.autoplay = settings.autoPlay;
  67503. }
  67504. if (settings.loop !== undefined) {
  67505. _this.video.loop = settings.loop;
  67506. }
  67507. _this.video.setAttribute("playsinline", "");
  67508. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67509. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67510. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67511. _this.video.addEventListener("emptied", _this.reset);
  67512. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67513. _this._createInternalTexture();
  67514. }
  67515. if (settings.poster) {
  67516. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67517. _this._poster = true;
  67518. }
  67519. return _this;
  67520. }
  67521. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67522. get: function () {
  67523. if (!this._onUserActionRequestedObservable) {
  67524. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67525. }
  67526. return this._onUserActionRequestedObservable;
  67527. },
  67528. enumerable: true,
  67529. configurable: true
  67530. });
  67531. VideoTexture.prototype._getName = function (src) {
  67532. if (src instanceof HTMLVideoElement) {
  67533. return src.currentSrc;
  67534. }
  67535. if (typeof src === "object") {
  67536. return src.toString();
  67537. }
  67538. return src;
  67539. };
  67540. ;
  67541. VideoTexture.prototype._getVideo = function (src) {
  67542. if (src instanceof HTMLVideoElement) {
  67543. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67544. return src;
  67545. }
  67546. var video = document.createElement("video");
  67547. if (typeof src === "string") {
  67548. BABYLON.Tools.SetCorsBehavior(src, video);
  67549. video.src = src;
  67550. }
  67551. else {
  67552. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67553. src.forEach(function (url) {
  67554. var source = document.createElement("source");
  67555. source.src = url;
  67556. video.appendChild(source);
  67557. });
  67558. }
  67559. return video;
  67560. };
  67561. ;
  67562. /**
  67563. * @hidden Internal method to initiate `update`.
  67564. */
  67565. VideoTexture.prototype._rebuild = function () {
  67566. this.update();
  67567. };
  67568. /**
  67569. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67570. */
  67571. VideoTexture.prototype.update = function () {
  67572. if (!this.autoUpdateTexture) {
  67573. // Expecting user to call `updateTexture` manually
  67574. return;
  67575. }
  67576. this.updateTexture(true);
  67577. };
  67578. /**
  67579. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67580. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67581. */
  67582. VideoTexture.prototype.updateTexture = function (isVisible) {
  67583. if (!isVisible) {
  67584. return;
  67585. }
  67586. if (this.video.paused && this._stillImageCaptured) {
  67587. return;
  67588. }
  67589. this._stillImageCaptured = true;
  67590. this._updateInternalTexture();
  67591. };
  67592. /**
  67593. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67594. * @param url New url.
  67595. */
  67596. VideoTexture.prototype.updateURL = function (url) {
  67597. this.video.src = url;
  67598. };
  67599. VideoTexture.prototype.dispose = function () {
  67600. _super.prototype.dispose.call(this);
  67601. if (this._onUserActionRequestedObservable) {
  67602. this._onUserActionRequestedObservable.clear();
  67603. this._onUserActionRequestedObservable = null;
  67604. }
  67605. this.video.removeEventListener("canplay", this._createInternalTexture);
  67606. this.video.removeEventListener("paused", this._updateInternalTexture);
  67607. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67608. this.video.removeEventListener("emptied", this.reset);
  67609. this.video.pause();
  67610. };
  67611. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67612. var video = document.createElement("video");
  67613. video.setAttribute('autoplay', '');
  67614. video.setAttribute('muted', '');
  67615. video.setAttribute('playsinline', '');
  67616. var constraintsDeviceId;
  67617. if (constraints && constraints.deviceId) {
  67618. constraintsDeviceId = {
  67619. exact: constraints.deviceId,
  67620. };
  67621. }
  67622. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67623. if (navigator.mediaDevices) {
  67624. navigator.mediaDevices.getUserMedia({ video: constraints })
  67625. .then(function (stream) {
  67626. if (video.mozSrcObject !== undefined) {
  67627. // hack for Firefox < 19
  67628. video.mozSrcObject = stream;
  67629. }
  67630. else {
  67631. video.srcObject = stream;
  67632. }
  67633. var onPlaying = function () {
  67634. if (onReady) {
  67635. onReady(new VideoTexture("video", video, scene, true, true));
  67636. }
  67637. video.removeEventListener("playing", onPlaying);
  67638. };
  67639. video.addEventListener("playing", onPlaying);
  67640. video.play();
  67641. })
  67642. .catch(function (err) {
  67643. BABYLON.Tools.Error(err.name);
  67644. });
  67645. }
  67646. else {
  67647. navigator.getUserMedia =
  67648. navigator.getUserMedia ||
  67649. navigator.webkitGetUserMedia ||
  67650. navigator.mozGetUserMedia ||
  67651. navigator.msGetUserMedia;
  67652. if (navigator.getUserMedia) {
  67653. navigator.getUserMedia({
  67654. video: {
  67655. deviceId: constraintsDeviceId,
  67656. width: {
  67657. min: (constraints && constraints.minWidth) || 256,
  67658. max: (constraints && constraints.maxWidth) || 640,
  67659. },
  67660. height: {
  67661. min: (constraints && constraints.minHeight) || 256,
  67662. max: (constraints && constraints.maxHeight) || 480,
  67663. },
  67664. },
  67665. }, function (stream) {
  67666. if (video.mozSrcObject !== undefined) {
  67667. // hack for Firefox < 19
  67668. video.mozSrcObject = stream;
  67669. }
  67670. else {
  67671. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67672. }
  67673. video.play();
  67674. if (onReady) {
  67675. onReady(new VideoTexture("video", video, scene, true, true));
  67676. }
  67677. }, function (e) {
  67678. BABYLON.Tools.Error(e.name);
  67679. });
  67680. }
  67681. }
  67682. };
  67683. return VideoTexture;
  67684. }(BABYLON.Texture));
  67685. BABYLON.VideoTexture = VideoTexture;
  67686. })(BABYLON || (BABYLON = {}));
  67687. //# sourceMappingURL=babylon.videoTexture.js.map
  67688. var BABYLON;
  67689. (function (BABYLON) {
  67690. var RawTexture = /** @class */ (function (_super) {
  67691. __extends(RawTexture, _super);
  67692. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67693. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67694. if (invertY === void 0) { invertY = false; }
  67695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67696. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67697. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67698. _this.format = format;
  67699. _this._engine = scene.getEngine();
  67700. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67701. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67702. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67703. return _this;
  67704. }
  67705. RawTexture.prototype.update = function (data) {
  67706. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67707. };
  67708. // Statics
  67709. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67710. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67711. if (invertY === void 0) { invertY = false; }
  67712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67713. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  67714. };
  67715. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67716. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67717. if (invertY === void 0) { invertY = false; }
  67718. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67719. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67720. };
  67721. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67722. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67723. if (invertY === void 0) { invertY = false; }
  67724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67725. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67726. };
  67727. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67728. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67729. if (invertY === void 0) { invertY = false; }
  67730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67731. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67732. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67733. };
  67734. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67735. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67736. if (invertY === void 0) { invertY = false; }
  67737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67738. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67739. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67740. };
  67741. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67742. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67743. if (invertY === void 0) { invertY = false; }
  67744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67745. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67746. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67747. };
  67748. return RawTexture;
  67749. }(BABYLON.Texture));
  67750. BABYLON.RawTexture = RawTexture;
  67751. })(BABYLON || (BABYLON = {}));
  67752. //# sourceMappingURL=babylon.rawTexture.js.map
  67753. var BABYLON;
  67754. (function (BABYLON) {
  67755. /**
  67756. * Class used to store 3D textures containing user data
  67757. */
  67758. var RawTexture3D = /** @class */ (function (_super) {
  67759. __extends(RawTexture3D, _super);
  67760. /**
  67761. * Create a new RawTexture3D
  67762. * @param data defines the data of the texture
  67763. * @param width defines the width of the texture
  67764. * @param height defines the height of the texture
  67765. * @param depth defines the depth of the texture
  67766. * @param format defines the texture format to use
  67767. * @param scene defines the hosting scene
  67768. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67769. * @param invertY defines if texture must be stored with Y axis inverted
  67770. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67771. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  67772. */
  67773. function RawTexture3D(data, width, height, depth,
  67774. /** Gets or sets the texture format to use */
  67775. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  67776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67777. if (invertY === void 0) { invertY = false; }
  67778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67780. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67781. _this.format = format;
  67782. _this._engine = scene.getEngine();
  67783. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  67784. _this.is3D = true;
  67785. return _this;
  67786. }
  67787. /**
  67788. * Update the texture with new data
  67789. * @param data defines the data to store in the texture
  67790. */
  67791. RawTexture3D.prototype.update = function (data) {
  67792. if (!this._texture) {
  67793. return;
  67794. }
  67795. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67796. };
  67797. return RawTexture3D;
  67798. }(BABYLON.Texture));
  67799. BABYLON.RawTexture3D = RawTexture3D;
  67800. })(BABYLON || (BABYLON = {}));
  67801. //# sourceMappingURL=babylon.rawTexture3D.js.map
  67802. var BABYLON;
  67803. (function (BABYLON) {
  67804. /**
  67805. * PostProcessManager is used to manage one or more post processes or post process pipelines
  67806. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67807. */
  67808. var PostProcessManager = /** @class */ (function () {
  67809. /**
  67810. * Creates a new instance PostProcess
  67811. * @param scene The scene that the post process is associated with.
  67812. */
  67813. function PostProcessManager(scene) {
  67814. this._vertexBuffers = {};
  67815. this._scene = scene;
  67816. }
  67817. PostProcessManager.prototype._prepareBuffers = function () {
  67818. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  67819. return;
  67820. }
  67821. // VBO
  67822. var vertices = [];
  67823. vertices.push(1, 1);
  67824. vertices.push(-1, 1);
  67825. vertices.push(-1, -1);
  67826. vertices.push(1, -1);
  67827. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67828. this._buildIndexBuffer();
  67829. };
  67830. PostProcessManager.prototype._buildIndexBuffer = function () {
  67831. // Indices
  67832. var indices = [];
  67833. indices.push(0);
  67834. indices.push(1);
  67835. indices.push(2);
  67836. indices.push(0);
  67837. indices.push(2);
  67838. indices.push(3);
  67839. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  67840. };
  67841. /**
  67842. * Rebuilds the vertex buffers of the manager.
  67843. * @hidden
  67844. */
  67845. PostProcessManager.prototype._rebuild = function () {
  67846. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67847. if (!vb) {
  67848. return;
  67849. }
  67850. vb._rebuild();
  67851. this._buildIndexBuffer();
  67852. };
  67853. // Methods
  67854. /**
  67855. * Prepares a frame to be run through a post process.
  67856. * @param sourceTexture The input texture to the post procesess. (default: null)
  67857. * @param postProcesses An array of post processes to be run. (default: null)
  67858. * @returns True if the post processes were able to be run.
  67859. * @hidden
  67860. */
  67861. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  67862. if (sourceTexture === void 0) { sourceTexture = null; }
  67863. if (postProcesses === void 0) { postProcesses = null; }
  67864. var camera = this._scene.activeCamera;
  67865. if (!camera) {
  67866. return false;
  67867. }
  67868. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67869. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67870. return false;
  67871. }
  67872. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  67873. return true;
  67874. };
  67875. /**
  67876. * Manually render a set of post processes to a texture.
  67877. * @param postProcesses An array of post processes to be run.
  67878. * @param targetTexture The target texture to render to.
  67879. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  67880. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  67881. * @param lodLevel defines which lod of the texture to render to
  67882. */
  67883. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  67884. if (targetTexture === void 0) { targetTexture = null; }
  67885. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67886. if (faceIndex === void 0) { faceIndex = 0; }
  67887. if (lodLevel === void 0) { lodLevel = 0; }
  67888. var engine = this._scene.getEngine();
  67889. for (var index = 0; index < postProcesses.length; index++) {
  67890. if (index < postProcesses.length - 1) {
  67891. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  67892. }
  67893. else {
  67894. if (targetTexture) {
  67895. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  67896. }
  67897. else {
  67898. engine.restoreDefaultFramebuffer();
  67899. }
  67900. }
  67901. var pp = postProcesses[index];
  67902. var effect = pp.apply();
  67903. if (effect) {
  67904. pp.onBeforeRenderObservable.notifyObservers(effect);
  67905. // VBOs
  67906. this._prepareBuffers();
  67907. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67908. // Draw order
  67909. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67910. pp.onAfterRenderObservable.notifyObservers(effect);
  67911. }
  67912. }
  67913. // Restore depth buffer
  67914. engine.setDepthBuffer(true);
  67915. engine.setDepthWrite(true);
  67916. };
  67917. /**
  67918. * Finalize the result of the output of the postprocesses.
  67919. * @param doNotPresent If true the result will not be displayed to the screen.
  67920. * @param targetTexture The target texture to render to.
  67921. * @param faceIndex The index of the face to bind the target texture to.
  67922. * @param postProcesses The array of post processes to render.
  67923. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  67924. * @hidden
  67925. */
  67926. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  67927. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67928. var camera = this._scene.activeCamera;
  67929. if (!camera) {
  67930. return;
  67931. }
  67932. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67933. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67934. return;
  67935. }
  67936. var engine = this._scene.getEngine();
  67937. for (var index = 0, len = postProcesses.length; index < len; index++) {
  67938. var pp = postProcesses[index];
  67939. if (index < len - 1) {
  67940. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  67941. }
  67942. else {
  67943. if (targetTexture) {
  67944. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  67945. pp._outputTexture = targetTexture;
  67946. }
  67947. else {
  67948. engine.restoreDefaultFramebuffer();
  67949. pp._outputTexture = null;
  67950. }
  67951. }
  67952. if (doNotPresent) {
  67953. break;
  67954. }
  67955. var effect = pp.apply();
  67956. if (effect) {
  67957. pp.onBeforeRenderObservable.notifyObservers(effect);
  67958. // VBOs
  67959. this._prepareBuffers();
  67960. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67961. // Draw order
  67962. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67963. pp.onAfterRenderObservable.notifyObservers(effect);
  67964. }
  67965. }
  67966. // Restore states
  67967. engine.setDepthBuffer(true);
  67968. engine.setDepthWrite(true);
  67969. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67970. };
  67971. /**
  67972. * Disposes of the post process manager.
  67973. */
  67974. PostProcessManager.prototype.dispose = function () {
  67975. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67976. if (buffer) {
  67977. buffer.dispose();
  67978. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67979. }
  67980. if (this._indexBuffer) {
  67981. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67982. this._indexBuffer = null;
  67983. }
  67984. };
  67985. return PostProcessManager;
  67986. }());
  67987. BABYLON.PostProcessManager = PostProcessManager;
  67988. })(BABYLON || (BABYLON = {}));
  67989. //# sourceMappingURL=babylon.postProcessManager.js.map
  67990. var BABYLON;
  67991. (function (BABYLON) {
  67992. /**
  67993. * PostProcess can be used to apply a shader to a texture after it has been rendered
  67994. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67995. */
  67996. var PostProcess = /** @class */ (function () {
  67997. /**
  67998. * Creates a new instance PostProcess
  67999. * @param name The name of the PostProcess.
  68000. * @param fragmentUrl The url of the fragment shader to be used.
  68001. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68002. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68003. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68004. * @param camera The camera to apply the render pass to.
  68005. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68006. * @param engine The engine which the post process will be applied. (default: current engine)
  68007. * @param reusable If the post process can be reused on the same frame. (default: false)
  68008. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68009. * @param textureType Type of textures used when performing the post process. (default: 0)
  68010. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68011. * @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
  68012. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68013. */
  68014. function PostProcess(
  68015. /** Name of the PostProcess. */
  68016. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68018. if (defines === void 0) { defines = null; }
  68019. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68020. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68021. if (blockCompilation === void 0) { blockCompilation = false; }
  68022. this.name = name;
  68023. /**
  68024. * Width of the texture to apply the post process on
  68025. */
  68026. this.width = -1;
  68027. /**
  68028. * Height of the texture to apply the post process on
  68029. */
  68030. this.height = -1;
  68031. /**
  68032. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68033. * @hidden
  68034. */
  68035. this._outputTexture = null;
  68036. /**
  68037. * If the buffer needs to be cleared before applying the post process. (default: true)
  68038. * Should be set to false if shader will overwrite all previous pixels.
  68039. */
  68040. this.autoClear = true;
  68041. /**
  68042. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68043. */
  68044. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68045. /**
  68046. * Animations to be used for the post processing
  68047. */
  68048. this.animations = new Array();
  68049. /**
  68050. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68051. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68052. */
  68053. this.enablePixelPerfectMode = false;
  68054. /**
  68055. * Force the postprocess to be applied without taking in account viewport
  68056. */
  68057. this.forceFullscreenViewport = true;
  68058. /**
  68059. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68060. *
  68061. * | Value | Type | Description |
  68062. * | ----- | ----------------------------------- | ----------- |
  68063. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68064. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68065. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68066. *
  68067. */
  68068. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68069. /**
  68070. * Force textures to be a power of two (default: false)
  68071. */
  68072. this.alwaysForcePOT = false;
  68073. this._samples = 1;
  68074. /**
  68075. * Modify the scale of the post process to be the same as the viewport (default: false)
  68076. */
  68077. this.adaptScaleToCurrentViewport = false;
  68078. this._reusable = false;
  68079. /**
  68080. * Smart array of input and output textures for the post process.
  68081. * @hidden
  68082. */
  68083. this._textures = new BABYLON.SmartArray(2);
  68084. /**
  68085. * The index in _textures that corresponds to the output texture.
  68086. * @hidden
  68087. */
  68088. this._currentRenderTextureInd = 0;
  68089. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68090. this._texelSize = BABYLON.Vector2.Zero();
  68091. // Events
  68092. /**
  68093. * An event triggered when the postprocess is activated.
  68094. */
  68095. this.onActivateObservable = new BABYLON.Observable();
  68096. /**
  68097. * An event triggered when the postprocess changes its size.
  68098. */
  68099. this.onSizeChangedObservable = new BABYLON.Observable();
  68100. /**
  68101. * An event triggered when the postprocess applies its effect.
  68102. */
  68103. this.onApplyObservable = new BABYLON.Observable();
  68104. /**
  68105. * An event triggered before rendering the postprocess
  68106. */
  68107. this.onBeforeRenderObservable = new BABYLON.Observable();
  68108. /**
  68109. * An event triggered after rendering the postprocess
  68110. */
  68111. this.onAfterRenderObservable = new BABYLON.Observable();
  68112. if (camera != null) {
  68113. this._camera = camera;
  68114. this._scene = camera.getScene();
  68115. camera.attachPostProcess(this);
  68116. this._engine = this._scene.getEngine();
  68117. this._scene.postProcesses.push(this);
  68118. }
  68119. else if (engine) {
  68120. this._engine = engine;
  68121. this._engine.postProcesses.push(this);
  68122. }
  68123. this._options = options;
  68124. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68125. this._reusable = reusable || false;
  68126. this._textureType = textureType;
  68127. this._samplers = samplers || [];
  68128. this._samplers.push("textureSampler");
  68129. this._fragmentUrl = fragmentUrl;
  68130. this._vertexUrl = vertexUrl;
  68131. this._parameters = parameters || [];
  68132. this._parameters.push("scale");
  68133. this._indexParameters = indexParameters;
  68134. if (!blockCompilation) {
  68135. this.updateEffect(defines);
  68136. }
  68137. }
  68138. Object.defineProperty(PostProcess.prototype, "samples", {
  68139. /**
  68140. * Number of sample textures (default: 1)
  68141. */
  68142. get: function () {
  68143. return this._samples;
  68144. },
  68145. set: function (n) {
  68146. var _this = this;
  68147. this._samples = n;
  68148. this._textures.forEach(function (texture) {
  68149. if (texture.samples !== _this._samples) {
  68150. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68151. }
  68152. });
  68153. },
  68154. enumerable: true,
  68155. configurable: true
  68156. });
  68157. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68158. /**
  68159. * A function that is added to the onActivateObservable
  68160. */
  68161. set: function (callback) {
  68162. if (this._onActivateObserver) {
  68163. this.onActivateObservable.remove(this._onActivateObserver);
  68164. }
  68165. if (callback) {
  68166. this._onActivateObserver = this.onActivateObservable.add(callback);
  68167. }
  68168. },
  68169. enumerable: true,
  68170. configurable: true
  68171. });
  68172. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68173. /**
  68174. * A function that is added to the onSizeChangedObservable
  68175. */
  68176. set: function (callback) {
  68177. if (this._onSizeChangedObserver) {
  68178. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68179. }
  68180. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68181. },
  68182. enumerable: true,
  68183. configurable: true
  68184. });
  68185. Object.defineProperty(PostProcess.prototype, "onApply", {
  68186. /**
  68187. * A function that is added to the onApplyObservable
  68188. */
  68189. set: function (callback) {
  68190. if (this._onApplyObserver) {
  68191. this.onApplyObservable.remove(this._onApplyObserver);
  68192. }
  68193. this._onApplyObserver = this.onApplyObservable.add(callback);
  68194. },
  68195. enumerable: true,
  68196. configurable: true
  68197. });
  68198. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68199. /**
  68200. * A function that is added to the onBeforeRenderObservable
  68201. */
  68202. set: function (callback) {
  68203. if (this._onBeforeRenderObserver) {
  68204. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68205. }
  68206. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68207. },
  68208. enumerable: true,
  68209. configurable: true
  68210. });
  68211. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68212. /**
  68213. * A function that is added to the onAfterRenderObservable
  68214. */
  68215. set: function (callback) {
  68216. if (this._onAfterRenderObserver) {
  68217. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68218. }
  68219. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68220. },
  68221. enumerable: true,
  68222. configurable: true
  68223. });
  68224. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68225. /**
  68226. * 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
  68227. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68228. */
  68229. get: function () {
  68230. return this._textures.data[this._currentRenderTextureInd];
  68231. },
  68232. set: function (value) {
  68233. this._forcedOutputTexture = value;
  68234. },
  68235. enumerable: true,
  68236. configurable: true
  68237. });
  68238. /**
  68239. * Gets the camera which post process is applied to.
  68240. * @returns The camera the post process is applied to.
  68241. */
  68242. PostProcess.prototype.getCamera = function () {
  68243. return this._camera;
  68244. };
  68245. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68246. /**
  68247. * Gets the texel size of the postprocess.
  68248. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68249. */
  68250. get: function () {
  68251. if (this._shareOutputWithPostProcess) {
  68252. return this._shareOutputWithPostProcess.texelSize;
  68253. }
  68254. if (this._forcedOutputTexture) {
  68255. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68256. }
  68257. return this._texelSize;
  68258. },
  68259. enumerable: true,
  68260. configurable: true
  68261. });
  68262. /**
  68263. * Gets the engine which this post process belongs to.
  68264. * @returns The engine the post process was enabled with.
  68265. */
  68266. PostProcess.prototype.getEngine = function () {
  68267. return this._engine;
  68268. };
  68269. /**
  68270. * The effect that is created when initializing the post process.
  68271. * @returns The created effect corrisponding the the postprocess.
  68272. */
  68273. PostProcess.prototype.getEffect = function () {
  68274. return this._effect;
  68275. };
  68276. /**
  68277. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68278. * @param postProcess The post process to share the output with.
  68279. * @returns This post process.
  68280. */
  68281. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68282. this._disposeTextures();
  68283. this._shareOutputWithPostProcess = postProcess;
  68284. return this;
  68285. };
  68286. /**
  68287. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68288. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68289. */
  68290. PostProcess.prototype.useOwnOutput = function () {
  68291. if (this._textures.length == 0) {
  68292. this._textures = new BABYLON.SmartArray(2);
  68293. }
  68294. this._shareOutputWithPostProcess = null;
  68295. };
  68296. /**
  68297. * Updates the effect with the current post process compile time values and recompiles the shader.
  68298. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68299. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68300. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68301. * @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
  68302. * @param onCompiled Called when the shader has been compiled.
  68303. * @param onError Called if there is an error when compiling a shader.
  68304. */
  68305. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68306. if (defines === void 0) { defines = null; }
  68307. if (uniforms === void 0) { uniforms = null; }
  68308. if (samplers === void 0) { samplers = null; }
  68309. 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);
  68310. };
  68311. /**
  68312. * The post process is reusable if it can be used multiple times within one frame.
  68313. * @returns If the post process is reusable
  68314. */
  68315. PostProcess.prototype.isReusable = function () {
  68316. return this._reusable;
  68317. };
  68318. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68319. PostProcess.prototype.markTextureDirty = function () {
  68320. this.width = -1;
  68321. };
  68322. /**
  68323. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68324. * 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.
  68325. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68326. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68327. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68328. * @returns The target texture that was bound to be written to.
  68329. */
  68330. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68331. var _this = this;
  68332. if (sourceTexture === void 0) { sourceTexture = null; }
  68333. camera = camera || this._camera;
  68334. var scene = camera.getScene();
  68335. var engine = scene.getEngine();
  68336. var maxSize = engine.getCaps().maxTextureSize;
  68337. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68338. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68339. // 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
  68340. var webVRCamera = camera.parent;
  68341. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68342. requiredWidth /= 2;
  68343. }
  68344. var desiredWidth = (this._options.width || requiredWidth);
  68345. var desiredHeight = this._options.height || requiredHeight;
  68346. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68347. if (this.adaptScaleToCurrentViewport) {
  68348. var currentViewport = engine.currentViewport;
  68349. if (currentViewport) {
  68350. desiredWidth *= currentViewport.width;
  68351. desiredHeight *= currentViewport.height;
  68352. }
  68353. }
  68354. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68355. if (!this._options.width) {
  68356. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68357. }
  68358. if (!this._options.height) {
  68359. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68360. }
  68361. }
  68362. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68363. if (this._textures.length > 0) {
  68364. for (var i = 0; i < this._textures.length; i++) {
  68365. this._engine._releaseTexture(this._textures.data[i]);
  68366. }
  68367. this._textures.reset();
  68368. }
  68369. this.width = desiredWidth;
  68370. this.height = desiredHeight;
  68371. var textureSize = { width: this.width, height: this.height };
  68372. var textureOptions = {
  68373. generateMipMaps: false,
  68374. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68375. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68376. samplingMode: this.renderTargetSamplingMode,
  68377. type: this._textureType
  68378. };
  68379. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68380. if (this._reusable) {
  68381. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68382. }
  68383. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68384. this.onSizeChangedObservable.notifyObservers(this);
  68385. }
  68386. this._textures.forEach(function (texture) {
  68387. if (texture.samples !== _this.samples) {
  68388. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68389. }
  68390. });
  68391. }
  68392. var target;
  68393. if (this._shareOutputWithPostProcess) {
  68394. target = this._shareOutputWithPostProcess.inputTexture;
  68395. }
  68396. else if (this._forcedOutputTexture) {
  68397. target = this._forcedOutputTexture;
  68398. this.width = this._forcedOutputTexture.width;
  68399. this.height = this._forcedOutputTexture.height;
  68400. }
  68401. else {
  68402. target = this.inputTexture;
  68403. }
  68404. // Bind the input of this post process to be used as the output of the previous post process.
  68405. if (this.enablePixelPerfectMode) {
  68406. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68407. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68408. }
  68409. else {
  68410. this._scaleRatio.copyFromFloats(1, 1);
  68411. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68412. }
  68413. this.onActivateObservable.notifyObservers(camera);
  68414. // Clear
  68415. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68416. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68417. }
  68418. if (this._reusable) {
  68419. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68420. }
  68421. return target;
  68422. };
  68423. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68424. /**
  68425. * If the post process is supported.
  68426. */
  68427. get: function () {
  68428. return this._effect.isSupported;
  68429. },
  68430. enumerable: true,
  68431. configurable: true
  68432. });
  68433. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68434. /**
  68435. * The aspect ratio of the output texture.
  68436. */
  68437. get: function () {
  68438. if (this._shareOutputWithPostProcess) {
  68439. return this._shareOutputWithPostProcess.aspectRatio;
  68440. }
  68441. if (this._forcedOutputTexture) {
  68442. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68443. }
  68444. return this.width / this.height;
  68445. },
  68446. enumerable: true,
  68447. configurable: true
  68448. });
  68449. /**
  68450. * Get a value indicating if the post-process is ready to be used
  68451. * @returns true if the post-process is ready (shader is compiled)
  68452. */
  68453. PostProcess.prototype.isReady = function () {
  68454. return this._effect && this._effect.isReady();
  68455. };
  68456. /**
  68457. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68458. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68459. */
  68460. PostProcess.prototype.apply = function () {
  68461. // Check
  68462. if (!this._effect || !this._effect.isReady())
  68463. return null;
  68464. // States
  68465. this._engine.enableEffect(this._effect);
  68466. this._engine.setState(false);
  68467. this._engine.setDepthBuffer(false);
  68468. this._engine.setDepthWrite(false);
  68469. // Alpha
  68470. this._engine.setAlphaMode(this.alphaMode);
  68471. if (this.alphaConstants) {
  68472. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68473. }
  68474. // Bind the output texture of the preivous post process as the input to this post process.
  68475. var source;
  68476. if (this._shareOutputWithPostProcess) {
  68477. source = this._shareOutputWithPostProcess.inputTexture;
  68478. }
  68479. else if (this._forcedOutputTexture) {
  68480. source = this._forcedOutputTexture;
  68481. }
  68482. else {
  68483. source = this.inputTexture;
  68484. }
  68485. this._effect._bindTexture("textureSampler", source);
  68486. // Parameters
  68487. this._effect.setVector2("scale", this._scaleRatio);
  68488. this.onApplyObservable.notifyObservers(this._effect);
  68489. return this._effect;
  68490. };
  68491. PostProcess.prototype._disposeTextures = function () {
  68492. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68493. return;
  68494. }
  68495. if (this._textures.length > 0) {
  68496. for (var i = 0; i < this._textures.length; i++) {
  68497. this._engine._releaseTexture(this._textures.data[i]);
  68498. }
  68499. }
  68500. this._textures.dispose();
  68501. };
  68502. /**
  68503. * Disposes the post process.
  68504. * @param camera The camera to dispose the post process on.
  68505. */
  68506. PostProcess.prototype.dispose = function (camera) {
  68507. camera = camera || this._camera;
  68508. this._disposeTextures();
  68509. if (this._scene) {
  68510. var index_1 = this._scene.postProcesses.indexOf(this);
  68511. if (index_1 !== -1) {
  68512. this._scene.postProcesses.splice(index_1, 1);
  68513. }
  68514. }
  68515. else {
  68516. var index_2 = this._engine.postProcesses.indexOf(this);
  68517. if (index_2 !== -1) {
  68518. this._engine.postProcesses.splice(index_2, 1);
  68519. }
  68520. }
  68521. if (!camera) {
  68522. return;
  68523. }
  68524. camera.detachPostProcess(this);
  68525. var index = camera._postProcesses.indexOf(this);
  68526. if (index === 0 && camera._postProcesses.length > 0) {
  68527. var firstPostProcess = this._camera._getFirstPostProcess();
  68528. if (firstPostProcess) {
  68529. firstPostProcess.markTextureDirty();
  68530. }
  68531. }
  68532. this.onActivateObservable.clear();
  68533. this.onAfterRenderObservable.clear();
  68534. this.onApplyObservable.clear();
  68535. this.onBeforeRenderObservable.clear();
  68536. this.onSizeChangedObservable.clear();
  68537. };
  68538. return PostProcess;
  68539. }());
  68540. BABYLON.PostProcess = PostProcess;
  68541. })(BABYLON || (BABYLON = {}));
  68542. //# sourceMappingURL=babylon.postProcess.js.map
  68543. var BABYLON;
  68544. (function (BABYLON) {
  68545. var PassPostProcess = /** @class */ (function (_super) {
  68546. __extends(PassPostProcess, _super);
  68547. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68548. if (camera === void 0) { camera = null; }
  68549. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68550. if (blockCompilation === void 0) { blockCompilation = false; }
  68551. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68552. }
  68553. return PassPostProcess;
  68554. }(BABYLON.PostProcess));
  68555. BABYLON.PassPostProcess = PassPostProcess;
  68556. })(BABYLON || (BABYLON = {}));
  68557. //# sourceMappingURL=babylon.passPostProcess.js.map
  68558. var __assign = (this && this.__assign) || function () {
  68559. __assign = Object.assign || function(t) {
  68560. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68561. s = arguments[i];
  68562. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68563. t[p] = s[p];
  68564. }
  68565. return t;
  68566. };
  68567. return __assign.apply(this, arguments);
  68568. };
  68569. var BABYLON;
  68570. (function (BABYLON) {
  68571. /**
  68572. * Default implementation IShadowGenerator.
  68573. * This is the main object responsible of generating shadows in the framework.
  68574. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68575. */
  68576. var ShadowGenerator = /** @class */ (function () {
  68577. /**
  68578. * Creates a ShadowGenerator object.
  68579. * A ShadowGenerator is the required tool to use the shadows.
  68580. * Each light casting shadows needs to use its own ShadowGenerator.
  68581. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68582. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68583. * @param light The light object generating the shadows.
  68584. * @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.
  68585. */
  68586. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68587. this._bias = 0.00005;
  68588. this._normalBias = 0;
  68589. this._blurBoxOffset = 1;
  68590. this._blurScale = 2;
  68591. this._blurKernel = 1;
  68592. this._useKernelBlur = false;
  68593. this._filter = ShadowGenerator.FILTER_NONE;
  68594. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68595. this._contactHardeningLightSizeUVRatio = 0.1;
  68596. this._darkness = 0;
  68597. this._transparencyShadow = false;
  68598. /**
  68599. * Controls the extent to which the shadows fade out at the edge of the frustum
  68600. * Used only by directionals and spots
  68601. */
  68602. this.frustumEdgeFalloff = 0;
  68603. /**
  68604. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68605. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68606. * It might on the other hand introduce peter panning.
  68607. */
  68608. this.forceBackFacesOnly = false;
  68609. this._lightDirection = BABYLON.Vector3.Zero();
  68610. this._viewMatrix = BABYLON.Matrix.Zero();
  68611. this._projectionMatrix = BABYLON.Matrix.Zero();
  68612. this._transformMatrix = BABYLON.Matrix.Zero();
  68613. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68614. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68615. this._currentFaceIndex = 0;
  68616. this._currentFaceIndexCache = 0;
  68617. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68618. this._mapSize = mapSize;
  68619. this._light = light;
  68620. this._scene = light.getScene();
  68621. light._shadowGenerator = this;
  68622. // Texture type fallback from float to int if not supported.
  68623. var caps = this._scene.getEngine().getCaps();
  68624. if (!useFullFloatFirst) {
  68625. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68626. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68627. }
  68628. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68629. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68630. }
  68631. else {
  68632. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68633. }
  68634. }
  68635. else {
  68636. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68637. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68638. }
  68639. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68640. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68641. }
  68642. else {
  68643. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68644. }
  68645. }
  68646. this._initializeGenerator();
  68647. this._applyFilterValues();
  68648. }
  68649. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68650. /**
  68651. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68652. */
  68653. get: function () {
  68654. return this._bias;
  68655. },
  68656. /**
  68657. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68658. */
  68659. set: function (bias) {
  68660. this._bias = bias;
  68661. },
  68662. enumerable: true,
  68663. configurable: true
  68664. });
  68665. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68666. /**
  68667. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68668. */
  68669. get: function () {
  68670. return this._normalBias;
  68671. },
  68672. /**
  68673. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68674. */
  68675. set: function (normalBias) {
  68676. this._normalBias = normalBias;
  68677. },
  68678. enumerable: true,
  68679. configurable: true
  68680. });
  68681. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68682. /**
  68683. * Gets the blur box offset: offset applied during the blur pass.
  68684. * Only usefull if useKernelBlur = false
  68685. */
  68686. get: function () {
  68687. return this._blurBoxOffset;
  68688. },
  68689. /**
  68690. * Sets the blur box offset: offset applied during the blur pass.
  68691. * Only usefull if useKernelBlur = false
  68692. */
  68693. set: function (value) {
  68694. if (this._blurBoxOffset === value) {
  68695. return;
  68696. }
  68697. this._blurBoxOffset = value;
  68698. this._disposeBlurPostProcesses();
  68699. },
  68700. enumerable: true,
  68701. configurable: true
  68702. });
  68703. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68704. /**
  68705. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68706. * 2 means half of the size.
  68707. */
  68708. get: function () {
  68709. return this._blurScale;
  68710. },
  68711. /**
  68712. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68713. * 2 means half of the size.
  68714. */
  68715. set: function (value) {
  68716. if (this._blurScale === value) {
  68717. return;
  68718. }
  68719. this._blurScale = value;
  68720. this._disposeBlurPostProcesses();
  68721. },
  68722. enumerable: true,
  68723. configurable: true
  68724. });
  68725. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  68726. /**
  68727. * Gets the blur kernel: kernel size of the blur pass.
  68728. * Only usefull if useKernelBlur = true
  68729. */
  68730. get: function () {
  68731. return this._blurKernel;
  68732. },
  68733. /**
  68734. * Sets the blur kernel: kernel size of the blur pass.
  68735. * Only usefull if useKernelBlur = true
  68736. */
  68737. set: function (value) {
  68738. if (this._blurKernel === value) {
  68739. return;
  68740. }
  68741. this._blurKernel = value;
  68742. this._disposeBlurPostProcesses();
  68743. },
  68744. enumerable: true,
  68745. configurable: true
  68746. });
  68747. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  68748. /**
  68749. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  68750. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68751. */
  68752. get: function () {
  68753. return this._useKernelBlur;
  68754. },
  68755. /**
  68756. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  68757. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68758. */
  68759. set: function (value) {
  68760. if (this._useKernelBlur === value) {
  68761. return;
  68762. }
  68763. this._useKernelBlur = value;
  68764. this._disposeBlurPostProcesses();
  68765. },
  68766. enumerable: true,
  68767. configurable: true
  68768. });
  68769. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68770. /**
  68771. * Gets the depth scale used in ESM mode.
  68772. */
  68773. get: function () {
  68774. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  68775. },
  68776. /**
  68777. * Sets the depth scale used in ESM mode.
  68778. * This can override the scale stored on the light.
  68779. */
  68780. set: function (value) {
  68781. this._depthScale = value;
  68782. },
  68783. enumerable: true,
  68784. configurable: true
  68785. });
  68786. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  68787. /**
  68788. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  68789. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68790. */
  68791. get: function () {
  68792. return this._filter;
  68793. },
  68794. /**
  68795. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  68796. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68797. */
  68798. set: function (value) {
  68799. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  68800. if (this._light.needCube()) {
  68801. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68802. this.useExponentialShadowMap = true;
  68803. return;
  68804. }
  68805. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68806. this.useCloseExponentialShadowMap = true;
  68807. return;
  68808. }
  68809. // PCF on cubemap would also be expensive
  68810. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68811. this.usePoissonSampling = true;
  68812. return;
  68813. }
  68814. }
  68815. // Weblg1 fallback for PCF.
  68816. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68817. if (this._scene.getEngine().webGLVersion === 1) {
  68818. this.usePoissonSampling = true;
  68819. return;
  68820. }
  68821. }
  68822. if (this._filter === value) {
  68823. return;
  68824. }
  68825. this._filter = value;
  68826. this._disposeBlurPostProcesses();
  68827. this._applyFilterValues();
  68828. this._light._markMeshesAsLightDirty();
  68829. },
  68830. enumerable: true,
  68831. configurable: true
  68832. });
  68833. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  68834. /**
  68835. * Gets if the current filter is set to Poisson Sampling.
  68836. */
  68837. get: function () {
  68838. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  68839. },
  68840. /**
  68841. * Sets the current filter to Poisson Sampling.
  68842. */
  68843. set: function (value) {
  68844. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  68845. return;
  68846. }
  68847. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  68848. },
  68849. enumerable: true,
  68850. configurable: true
  68851. });
  68852. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  68853. /**
  68854. * Gets if the current filter is set to VSM.
  68855. * DEPRECATED. Should use useExponentialShadowMap instead.
  68856. */
  68857. get: function () {
  68858. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68859. return this.useExponentialShadowMap;
  68860. },
  68861. /**
  68862. * Sets the current filter is to VSM.
  68863. * DEPRECATED. Should use useExponentialShadowMap instead.
  68864. */
  68865. set: function (value) {
  68866. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68867. this.useExponentialShadowMap = value;
  68868. },
  68869. enumerable: true,
  68870. configurable: true
  68871. });
  68872. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  68873. /**
  68874. * Gets if the current filter is set to blurred VSM.
  68875. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68876. */
  68877. get: function () {
  68878. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68879. return this.useBlurExponentialShadowMap;
  68880. },
  68881. /**
  68882. * Sets the current filter is to blurred VSM.
  68883. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68884. */
  68885. set: function (value) {
  68886. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68887. this.useBlurExponentialShadowMap = value;
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  68893. /**
  68894. * Gets if the current filter is set to ESM.
  68895. */
  68896. get: function () {
  68897. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  68898. },
  68899. /**
  68900. * Sets the current filter is to ESM.
  68901. */
  68902. set: function (value) {
  68903. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  68904. return;
  68905. }
  68906. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68907. },
  68908. enumerable: true,
  68909. configurable: true
  68910. });
  68911. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  68912. /**
  68913. * Gets if the current filter is set to filtered ESM.
  68914. */
  68915. get: function () {
  68916. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  68917. },
  68918. /**
  68919. * Gets if the current filter is set to filtered ESM.
  68920. */
  68921. set: function (value) {
  68922. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68923. return;
  68924. }
  68925. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68926. },
  68927. enumerable: true,
  68928. configurable: true
  68929. });
  68930. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  68931. /**
  68932. * Gets if the current filter is set to "close ESM" (using the inverse of the
  68933. * exponential to prevent steep falloff artifacts).
  68934. */
  68935. get: function () {
  68936. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  68937. },
  68938. /**
  68939. * Sets the current filter to "close ESM" (using the inverse of the
  68940. * exponential to prevent steep falloff artifacts).
  68941. */
  68942. set: function (value) {
  68943. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  68944. return;
  68945. }
  68946. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68947. },
  68948. enumerable: true,
  68949. configurable: true
  68950. });
  68951. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  68952. /**
  68953. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  68954. * exponential to prevent steep falloff artifacts).
  68955. */
  68956. get: function () {
  68957. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  68958. },
  68959. /**
  68960. * Sets the current filter to filtered "close ESM" (using the inverse of the
  68961. * exponential to prevent steep falloff artifacts).
  68962. */
  68963. set: function (value) {
  68964. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68965. return;
  68966. }
  68967. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68968. },
  68969. enumerable: true,
  68970. configurable: true
  68971. });
  68972. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  68973. /**
  68974. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  68975. */
  68976. get: function () {
  68977. return this.filter === ShadowGenerator.FILTER_PCF;
  68978. },
  68979. /**
  68980. * Sets the current filter to "PCF" (percentage closer filtering).
  68981. */
  68982. set: function (value) {
  68983. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  68984. return;
  68985. }
  68986. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  68987. },
  68988. enumerable: true,
  68989. configurable: true
  68990. });
  68991. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  68992. /**
  68993. * Gets the PCF or PCSS Quality.
  68994. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68995. */
  68996. get: function () {
  68997. return this._filteringQuality;
  68998. },
  68999. /**
  69000. * Sets the PCF or PCSS Quality.
  69001. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69002. */
  69003. set: function (filteringQuality) {
  69004. this._filteringQuality = filteringQuality;
  69005. },
  69006. enumerable: true,
  69007. configurable: true
  69008. });
  69009. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69010. /**
  69011. * Gets if the current filter is set to "PCSS" (contact hardening).
  69012. */
  69013. get: function () {
  69014. return this.filter === ShadowGenerator.FILTER_PCSS;
  69015. },
  69016. /**
  69017. * Sets the current filter to "PCSS" (contact hardening).
  69018. */
  69019. set: function (value) {
  69020. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69021. return;
  69022. }
  69023. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69024. },
  69025. enumerable: true,
  69026. configurable: true
  69027. });
  69028. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69029. /**
  69030. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69031. * Using a ratio helps keeping shape stability independently of the map size.
  69032. *
  69033. * It does not account for the light projection as it was having too much
  69034. * instability during the light setup or during light position changes.
  69035. *
  69036. * Only valid if useContactHardeningShadow is true.
  69037. */
  69038. get: function () {
  69039. return this._contactHardeningLightSizeUVRatio;
  69040. },
  69041. /**
  69042. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69043. * Using a ratio helps keeping shape stability independently of the map size.
  69044. *
  69045. * It does not account for the light projection as it was having too much
  69046. * instability during the light setup or during light position changes.
  69047. *
  69048. * Only valid if useContactHardeningShadow is true.
  69049. */
  69050. set: function (contactHardeningLightSizeUVRatio) {
  69051. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69052. },
  69053. enumerable: true,
  69054. configurable: true
  69055. });
  69056. /**
  69057. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69058. * 0 means strongest and 1 would means no shadow.
  69059. * @returns the darkness.
  69060. */
  69061. ShadowGenerator.prototype.getDarkness = function () {
  69062. return this._darkness;
  69063. };
  69064. /**
  69065. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69066. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69067. * @returns the shadow generator allowing fluent coding.
  69068. */
  69069. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69070. if (darkness >= 1.0)
  69071. this._darkness = 1.0;
  69072. else if (darkness <= 0.0)
  69073. this._darkness = 0.0;
  69074. else
  69075. this._darkness = darkness;
  69076. return this;
  69077. };
  69078. /**
  69079. * Sets the ability to have transparent shadow (boolean).
  69080. * @param transparent True if transparent else False
  69081. * @returns the shadow generator allowing fluent coding
  69082. */
  69083. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69084. this._transparencyShadow = transparent;
  69085. return this;
  69086. };
  69087. /**
  69088. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69089. * @returns The render target texture if present otherwise, null
  69090. */
  69091. ShadowGenerator.prototype.getShadowMap = function () {
  69092. return this._shadowMap;
  69093. };
  69094. /**
  69095. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69096. * @returns The render target texture if the shadow map is present otherwise, null
  69097. */
  69098. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69099. if (this._shadowMap2) {
  69100. return this._shadowMap2;
  69101. }
  69102. return this._shadowMap;
  69103. };
  69104. /**
  69105. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69106. * @param mesh Mesh to add
  69107. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69108. * @returns the Shadow Generator itself
  69109. */
  69110. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69111. if (includeDescendants === void 0) { includeDescendants = true; }
  69112. var _a;
  69113. if (!this._shadowMap) {
  69114. return this;
  69115. }
  69116. if (!this._shadowMap.renderList) {
  69117. this._shadowMap.renderList = [];
  69118. }
  69119. this._shadowMap.renderList.push(mesh);
  69120. if (includeDescendants) {
  69121. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69122. }
  69123. return this;
  69124. };
  69125. /**
  69126. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69127. * @param mesh Mesh to remove
  69128. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69129. * @returns the Shadow Generator itself
  69130. */
  69131. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69132. if (includeDescendants === void 0) { includeDescendants = true; }
  69133. if (!this._shadowMap || !this._shadowMap.renderList) {
  69134. return this;
  69135. }
  69136. var index = this._shadowMap.renderList.indexOf(mesh);
  69137. if (index !== -1) {
  69138. this._shadowMap.renderList.splice(index, 1);
  69139. }
  69140. if (includeDescendants) {
  69141. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69142. var child = _a[_i];
  69143. this.removeShadowCaster(child);
  69144. }
  69145. }
  69146. return this;
  69147. };
  69148. /**
  69149. * Returns the associated light object.
  69150. * @returns the light generating the shadow
  69151. */
  69152. ShadowGenerator.prototype.getLight = function () {
  69153. return this._light;
  69154. };
  69155. ShadowGenerator.prototype._initializeGenerator = function () {
  69156. this._light._markMeshesAsLightDirty();
  69157. this._initializeShadowMap();
  69158. };
  69159. ShadowGenerator.prototype._initializeShadowMap = function () {
  69160. var _this = this;
  69161. // Render target
  69162. var engine = this._scene.getEngine();
  69163. if (engine.webGLVersion > 1) {
  69164. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69165. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69166. }
  69167. else {
  69168. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69169. }
  69170. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69171. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69172. this._shadowMap.anisotropicFilteringLevel = 1;
  69173. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69174. this._shadowMap.renderParticles = false;
  69175. this._shadowMap.ignoreCameraViewport = true;
  69176. // Record Face Index before render.
  69177. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69178. _this._currentFaceIndex = faceIndex;
  69179. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69180. engine.setColorWrite(false);
  69181. }
  69182. });
  69183. // Custom render function.
  69184. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69185. // Blur if required afer render.
  69186. this._shadowMap.onAfterUnbindObservable.add(function () {
  69187. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69188. engine.setColorWrite(true);
  69189. }
  69190. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69191. return;
  69192. }
  69193. var shadowMap = _this.getShadowMapForRendering();
  69194. if (shadowMap) {
  69195. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69196. }
  69197. });
  69198. // Clear according to the chosen filter.
  69199. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69200. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69201. this._shadowMap.onClearObservable.add(function (engine) {
  69202. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69203. engine.clear(clearOne, false, true, false);
  69204. }
  69205. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69206. engine.clear(clearZero, true, true, false);
  69207. }
  69208. else {
  69209. engine.clear(clearOne, true, true, false);
  69210. }
  69211. });
  69212. };
  69213. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69214. var _this = this;
  69215. var engine = this._scene.getEngine();
  69216. var targetSize = this._mapSize / this.blurScale;
  69217. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69218. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69219. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69220. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69221. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69222. }
  69223. if (this.useKernelBlur) {
  69224. 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);
  69225. this._kernelBlurXPostprocess.width = targetSize;
  69226. this._kernelBlurXPostprocess.height = targetSize;
  69227. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69228. effect.setTexture("textureSampler", _this._shadowMap);
  69229. });
  69230. 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);
  69231. this._kernelBlurXPostprocess.autoClear = false;
  69232. this._kernelBlurYPostprocess.autoClear = false;
  69233. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69234. this._kernelBlurXPostprocess.packedFloat = true;
  69235. this._kernelBlurYPostprocess.packedFloat = true;
  69236. }
  69237. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69238. }
  69239. else {
  69240. 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);
  69241. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69242. effect.setFloat2("screenSize", targetSize, targetSize);
  69243. effect.setTexture("textureSampler", _this._shadowMap);
  69244. });
  69245. this._boxBlurPostprocess.autoClear = false;
  69246. this._blurPostProcesses = [this._boxBlurPostprocess];
  69247. }
  69248. };
  69249. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69250. var index;
  69251. var engine = this._scene.getEngine();
  69252. if (depthOnlySubMeshes.length) {
  69253. engine.setColorWrite(false);
  69254. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69255. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69256. }
  69257. engine.setColorWrite(true);
  69258. }
  69259. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69260. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69261. }
  69262. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69263. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69264. }
  69265. if (this._transparencyShadow) {
  69266. for (index = 0; index < transparentSubMeshes.length; index++) {
  69267. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69268. }
  69269. }
  69270. };
  69271. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69272. var _this = this;
  69273. var mesh = subMesh.getRenderingMesh();
  69274. var scene = this._scene;
  69275. var engine = scene.getEngine();
  69276. var material = subMesh.getMaterial();
  69277. if (!material) {
  69278. return;
  69279. }
  69280. // Culling
  69281. engine.setState(material.backFaceCulling);
  69282. // Managing instances
  69283. var batch = mesh._getInstancesRenderList(subMesh._id);
  69284. if (batch.mustReturn) {
  69285. return;
  69286. }
  69287. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69288. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69289. engine.enableEffect(this._effect);
  69290. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69291. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69292. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69293. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69294. this._effect.setVector3("lightData", this._cachedDirection);
  69295. }
  69296. else {
  69297. this._effect.setVector3("lightData", this._cachedPosition);
  69298. }
  69299. if (scene.activeCamera) {
  69300. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69301. }
  69302. // Alpha test
  69303. if (material && material.needAlphaTesting()) {
  69304. var alphaTexture = material.getAlphaTestTexture();
  69305. if (alphaTexture) {
  69306. this._effect.setTexture("diffuseSampler", alphaTexture);
  69307. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69308. }
  69309. }
  69310. // Bones
  69311. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69312. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69313. }
  69314. // Morph targets
  69315. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69316. if (this.forceBackFacesOnly) {
  69317. engine.setState(true, 0, false, true);
  69318. }
  69319. // Draw
  69320. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69321. if (this.forceBackFacesOnly) {
  69322. engine.setState(true, 0, false, false);
  69323. }
  69324. }
  69325. else {
  69326. // Need to reset refresh rate of the shadowMap
  69327. if (this._shadowMap) {
  69328. this._shadowMap.resetRefreshCounter();
  69329. }
  69330. }
  69331. };
  69332. ShadowGenerator.prototype._applyFilterValues = function () {
  69333. if (!this._shadowMap) {
  69334. return;
  69335. }
  69336. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69337. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69338. }
  69339. else {
  69340. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69341. }
  69342. };
  69343. /**
  69344. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69345. * @param onCompiled Callback triggered at the and of the effects compilation
  69346. * @param options Sets of optional options forcing the compilation with different modes
  69347. */
  69348. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69349. var _this = this;
  69350. var localOptions = __assign({ useInstances: false }, options);
  69351. var shadowMap = this.getShadowMap();
  69352. if (!shadowMap) {
  69353. if (onCompiled) {
  69354. onCompiled(this);
  69355. }
  69356. return;
  69357. }
  69358. var renderList = shadowMap.renderList;
  69359. if (!renderList) {
  69360. if (onCompiled) {
  69361. onCompiled(this);
  69362. }
  69363. return;
  69364. }
  69365. var subMeshes = new Array();
  69366. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69367. var mesh = renderList_1[_i];
  69368. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69369. }
  69370. if (subMeshes.length === 0) {
  69371. if (onCompiled) {
  69372. onCompiled(this);
  69373. }
  69374. return;
  69375. }
  69376. var currentIndex = 0;
  69377. var checkReady = function () {
  69378. if (!_this._scene || !_this._scene.getEngine()) {
  69379. return;
  69380. }
  69381. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69382. currentIndex++;
  69383. if (currentIndex >= subMeshes.length) {
  69384. if (onCompiled) {
  69385. onCompiled(_this);
  69386. }
  69387. return;
  69388. }
  69389. }
  69390. setTimeout(checkReady, 16);
  69391. };
  69392. checkReady();
  69393. };
  69394. /**
  69395. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69396. * @param options Sets of optional options forcing the compilation with different modes
  69397. * @returns A promise that resolves when the compilation completes
  69398. */
  69399. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69400. var _this = this;
  69401. return new Promise(function (resolve) {
  69402. _this.forceCompilation(function () {
  69403. resolve();
  69404. }, options);
  69405. });
  69406. };
  69407. /**
  69408. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69409. * @param subMesh The submesh we want to render in the shadow map
  69410. * @param useInstances Defines wether will draw in the map using instances
  69411. * @returns true if ready otherwise, false
  69412. */
  69413. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69414. var defines = [];
  69415. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69416. defines.push("#define FLOAT");
  69417. }
  69418. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69419. defines.push("#define ESM");
  69420. }
  69421. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69422. defines.push("#define DEPTHTEXTURE");
  69423. }
  69424. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69425. var mesh = subMesh.getMesh();
  69426. var material = subMesh.getMaterial();
  69427. // Normal bias.
  69428. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69429. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69430. defines.push("#define NORMAL");
  69431. if (mesh.nonUniformScaling) {
  69432. defines.push("#define NONUNIFORMSCALING");
  69433. }
  69434. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69435. defines.push("#define DIRECTIONINLIGHTDATA");
  69436. }
  69437. }
  69438. // Alpha test
  69439. if (material && material.needAlphaTesting()) {
  69440. var alphaTexture = material.getAlphaTestTexture();
  69441. if (alphaTexture) {
  69442. defines.push("#define ALPHATEST");
  69443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69444. attribs.push(BABYLON.VertexBuffer.UVKind);
  69445. defines.push("#define UV1");
  69446. }
  69447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69448. if (alphaTexture.coordinatesIndex === 1) {
  69449. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69450. defines.push("#define UV2");
  69451. }
  69452. }
  69453. }
  69454. }
  69455. // Bones
  69456. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69457. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69458. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69459. if (mesh.numBoneInfluencers > 4) {
  69460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69462. }
  69463. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69464. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69465. }
  69466. else {
  69467. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69468. }
  69469. // Morph targets
  69470. var manager = mesh.morphTargetManager;
  69471. var morphInfluencers = 0;
  69472. if (manager) {
  69473. if (manager.numInfluencers > 0) {
  69474. defines.push("#define MORPHTARGETS");
  69475. morphInfluencers = manager.numInfluencers;
  69476. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69477. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69478. }
  69479. }
  69480. // Instances
  69481. if (useInstances) {
  69482. defines.push("#define INSTANCES");
  69483. attribs.push("world0");
  69484. attribs.push("world1");
  69485. attribs.push("world2");
  69486. attribs.push("world3");
  69487. }
  69488. // Get correct effect
  69489. var join = defines.join("\n");
  69490. if (this._cachedDefines !== join) {
  69491. this._cachedDefines = join;
  69492. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69493. }
  69494. if (!this._effect.isReady()) {
  69495. return false;
  69496. }
  69497. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69498. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69499. this._initializeBlurRTTAndPostProcesses();
  69500. }
  69501. }
  69502. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69503. return false;
  69504. }
  69505. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69506. return false;
  69507. }
  69508. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69509. return false;
  69510. }
  69511. return true;
  69512. };
  69513. /**
  69514. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69515. * @param defines Defines of the material we want to update
  69516. * @param lightIndex Index of the light in the enabled light list of the material
  69517. */
  69518. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69519. var scene = this._scene;
  69520. var light = this._light;
  69521. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69522. return;
  69523. }
  69524. defines["SHADOW" + lightIndex] = true;
  69525. if (this.useContactHardeningShadow) {
  69526. defines["SHADOWPCSS" + lightIndex] = true;
  69527. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69528. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69529. }
  69530. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69531. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69532. }
  69533. // else default to high.
  69534. }
  69535. if (this.usePercentageCloserFiltering) {
  69536. defines["SHADOWPCF" + lightIndex] = true;
  69537. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69538. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69539. }
  69540. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69541. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69542. }
  69543. // else default to high.
  69544. }
  69545. else if (this.usePoissonSampling) {
  69546. defines["SHADOWPOISSON" + lightIndex] = true;
  69547. }
  69548. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69549. defines["SHADOWESM" + lightIndex] = true;
  69550. }
  69551. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69552. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69553. }
  69554. if (light.needCube()) {
  69555. defines["SHADOWCUBE" + lightIndex] = true;
  69556. }
  69557. };
  69558. /**
  69559. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69560. * defined in the generator but impacting the effect).
  69561. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69562. * @param effect The effect we are binfing the information for
  69563. */
  69564. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69565. var light = this._light;
  69566. var scene = this._scene;
  69567. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69568. return;
  69569. }
  69570. var camera = scene.activeCamera;
  69571. if (!camera) {
  69572. return;
  69573. }
  69574. var shadowMap = this.getShadowMap();
  69575. if (!shadowMap) {
  69576. return;
  69577. }
  69578. if (!light.needCube()) {
  69579. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69580. }
  69581. // Only PCF uses depth stencil texture.
  69582. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69583. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69584. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69585. }
  69586. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69587. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69588. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69589. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69590. }
  69591. else {
  69592. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69593. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69594. }
  69595. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69596. };
  69597. /**
  69598. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69599. * (eq to shadow prjection matrix * light transform matrix)
  69600. * @returns The transform matrix used to create the shadow map
  69601. */
  69602. ShadowGenerator.prototype.getTransformMatrix = function () {
  69603. var scene = this._scene;
  69604. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69605. return this._transformMatrix;
  69606. }
  69607. this._currentRenderID = scene.getRenderId();
  69608. this._currentFaceIndexCache = this._currentFaceIndex;
  69609. var lightPosition = this._light.position;
  69610. if (this._light.computeTransformedInformation()) {
  69611. lightPosition = this._light.transformedPosition;
  69612. }
  69613. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69614. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69615. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69616. }
  69617. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69618. this._cachedPosition.copyFrom(lightPosition);
  69619. this._cachedDirection.copyFrom(this._lightDirection);
  69620. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69621. var shadowMap = this.getShadowMap();
  69622. if (shadowMap) {
  69623. var renderList = shadowMap.renderList;
  69624. if (renderList) {
  69625. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69626. }
  69627. }
  69628. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69629. }
  69630. return this._transformMatrix;
  69631. };
  69632. /**
  69633. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69634. * Cube and 2D textures for instance.
  69635. */
  69636. ShadowGenerator.prototype.recreateShadowMap = function () {
  69637. var shadowMap = this._shadowMap;
  69638. if (!shadowMap) {
  69639. return;
  69640. }
  69641. // Track render list.
  69642. var renderList = shadowMap.renderList;
  69643. // Clean up existing data.
  69644. this._disposeRTTandPostProcesses();
  69645. // Reinitializes.
  69646. this._initializeGenerator();
  69647. // Reaffect the filter to ensure a correct fallback if necessary.
  69648. this.filter = this.filter;
  69649. // Reaffect the filter.
  69650. this._applyFilterValues();
  69651. // Reaffect Render List.
  69652. this._shadowMap.renderList = renderList;
  69653. };
  69654. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69655. if (this._shadowMap2) {
  69656. this._shadowMap2.dispose();
  69657. this._shadowMap2 = null;
  69658. }
  69659. if (this._boxBlurPostprocess) {
  69660. this._boxBlurPostprocess.dispose();
  69661. this._boxBlurPostprocess = null;
  69662. }
  69663. if (this._kernelBlurXPostprocess) {
  69664. this._kernelBlurXPostprocess.dispose();
  69665. this._kernelBlurXPostprocess = null;
  69666. }
  69667. if (this._kernelBlurYPostprocess) {
  69668. this._kernelBlurYPostprocess.dispose();
  69669. this._kernelBlurYPostprocess = null;
  69670. }
  69671. this._blurPostProcesses = [];
  69672. };
  69673. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69674. if (this._shadowMap) {
  69675. this._shadowMap.dispose();
  69676. this._shadowMap = null;
  69677. }
  69678. this._disposeBlurPostProcesses();
  69679. };
  69680. /**
  69681. * Disposes the ShadowGenerator.
  69682. * Returns nothing.
  69683. */
  69684. ShadowGenerator.prototype.dispose = function () {
  69685. this._disposeRTTandPostProcesses();
  69686. if (this._light) {
  69687. this._light._shadowGenerator = null;
  69688. this._light._markMeshesAsLightDirty();
  69689. }
  69690. };
  69691. /**
  69692. * Serializes the shadow generator setup to a json object.
  69693. * @returns The serialized JSON object
  69694. */
  69695. ShadowGenerator.prototype.serialize = function () {
  69696. var serializationObject = {};
  69697. var shadowMap = this.getShadowMap();
  69698. if (!shadowMap) {
  69699. return serializationObject;
  69700. }
  69701. serializationObject.lightId = this._light.id;
  69702. serializationObject.mapSize = shadowMap.getRenderSize();
  69703. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69704. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69705. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69706. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69707. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69708. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69709. serializationObject.depthScale = this.depthScale;
  69710. serializationObject.darkness = this.getDarkness();
  69711. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69712. serializationObject.blurKernel = this.blurKernel;
  69713. serializationObject.blurScale = this.blurScale;
  69714. serializationObject.useKernelBlur = this.useKernelBlur;
  69715. serializationObject.transparencyShadow = this._transparencyShadow;
  69716. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  69717. serializationObject.bias = this.bias;
  69718. serializationObject.normalBias = this.normalBias;
  69719. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  69720. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  69721. serializationObject.filteringQuality = this.filteringQuality;
  69722. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  69723. serializationObject.renderList = [];
  69724. if (shadowMap.renderList) {
  69725. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  69726. var mesh = shadowMap.renderList[meshIndex];
  69727. serializationObject.renderList.push(mesh.id);
  69728. }
  69729. }
  69730. return serializationObject;
  69731. };
  69732. /**
  69733. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  69734. * @param parsedShadowGenerator The JSON object to parse
  69735. * @param scene The scene to create the shadow map for
  69736. * @returns The parsed shadow generator
  69737. */
  69738. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  69739. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  69740. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  69741. var shadowMap = shadowGenerator.getShadowMap();
  69742. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  69743. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  69744. meshes.forEach(function (mesh) {
  69745. if (!shadowMap) {
  69746. return;
  69747. }
  69748. if (!shadowMap.renderList) {
  69749. shadowMap.renderList = [];
  69750. }
  69751. shadowMap.renderList.push(mesh);
  69752. });
  69753. }
  69754. if (parsedShadowGenerator.usePoissonSampling) {
  69755. shadowGenerator.usePoissonSampling = true;
  69756. }
  69757. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69758. shadowGenerator.useExponentialShadowMap = true;
  69759. }
  69760. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69761. shadowGenerator.useBlurExponentialShadowMap = true;
  69762. }
  69763. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69764. shadowGenerator.useCloseExponentialShadowMap = true;
  69765. }
  69766. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69767. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69768. }
  69769. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69770. shadowGenerator.usePercentageCloserFiltering = true;
  69771. }
  69772. else if (parsedShadowGenerator.useContactHardeningShadow) {
  69773. shadowGenerator.useContactHardeningShadow = true;
  69774. }
  69775. if (parsedShadowGenerator.filteringQuality) {
  69776. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  69777. }
  69778. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  69779. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  69780. }
  69781. // Backward compat
  69782. else if (parsedShadowGenerator.useVarianceShadowMap) {
  69783. shadowGenerator.useExponentialShadowMap = true;
  69784. }
  69785. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  69786. shadowGenerator.useBlurExponentialShadowMap = true;
  69787. }
  69788. if (parsedShadowGenerator.depthScale) {
  69789. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  69790. }
  69791. if (parsedShadowGenerator.blurScale) {
  69792. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  69793. }
  69794. if (parsedShadowGenerator.blurBoxOffset) {
  69795. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  69796. }
  69797. if (parsedShadowGenerator.useKernelBlur) {
  69798. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  69799. }
  69800. if (parsedShadowGenerator.blurKernel) {
  69801. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  69802. }
  69803. if (parsedShadowGenerator.bias !== undefined) {
  69804. shadowGenerator.bias = parsedShadowGenerator.bias;
  69805. }
  69806. if (parsedShadowGenerator.normalBias !== undefined) {
  69807. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  69808. }
  69809. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  69810. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  69811. }
  69812. if (parsedShadowGenerator.darkness) {
  69813. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  69814. }
  69815. if (parsedShadowGenerator.transparencyShadow) {
  69816. shadowGenerator.setTransparencyShadow(true);
  69817. }
  69818. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  69819. return shadowGenerator;
  69820. };
  69821. /**
  69822. * Shadow generator mode None: no filtering applied.
  69823. */
  69824. ShadowGenerator.FILTER_NONE = 0;
  69825. /**
  69826. * Shadow generator mode ESM: Exponential Shadow Mapping.
  69827. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69828. */
  69829. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  69830. /**
  69831. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  69832. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  69833. */
  69834. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  69835. /**
  69836. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  69837. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69838. */
  69839. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  69840. /**
  69841. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  69842. * edge artifacts on steep falloff.
  69843. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69844. */
  69845. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  69846. /**
  69847. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  69848. * edge artifacts on steep falloff.
  69849. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69850. */
  69851. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  69852. /**
  69853. * Shadow generator mode PCF: Percentage Closer Filtering
  69854. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69855. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  69856. */
  69857. ShadowGenerator.FILTER_PCF = 6;
  69858. /**
  69859. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  69860. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69861. * Contact Hardening
  69862. */
  69863. ShadowGenerator.FILTER_PCSS = 7;
  69864. /**
  69865. * Reserved for PCF and PCSS
  69866. * Highest Quality.
  69867. *
  69868. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  69869. *
  69870. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  69871. */
  69872. ShadowGenerator.QUALITY_HIGH = 0;
  69873. /**
  69874. * Reserved for PCF and PCSS
  69875. * Good tradeoff for quality/perf cross devices
  69876. *
  69877. * Execute PCF on a 3*3 kernel.
  69878. *
  69879. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  69880. */
  69881. ShadowGenerator.QUALITY_MEDIUM = 1;
  69882. /**
  69883. * Reserved for PCF and PCSS
  69884. * The lowest quality but the fastest.
  69885. *
  69886. * Execute PCF on a 1*1 kernel.
  69887. *
  69888. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  69889. */
  69890. ShadowGenerator.QUALITY_LOW = 2;
  69891. return ShadowGenerator;
  69892. }());
  69893. BABYLON.ShadowGenerator = ShadowGenerator;
  69894. })(BABYLON || (BABYLON = {}));
  69895. //# sourceMappingURL=babylon.shadowGenerator.js.map
  69896. var BABYLON;
  69897. (function (BABYLON) {
  69898. var DefaultLoadingScreen = /** @class */ (function () {
  69899. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  69900. if (_loadingText === void 0) { _loadingText = ""; }
  69901. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  69902. var _this = this;
  69903. this._renderingCanvas = _renderingCanvas;
  69904. this._loadingText = _loadingText;
  69905. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  69906. // Resize
  69907. this._resizeLoadingUI = function () {
  69908. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  69909. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  69910. if (!_this._loadingDiv) {
  69911. return;
  69912. }
  69913. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  69914. _this._loadingDiv.style.left = canvasRect.left + "px";
  69915. _this._loadingDiv.style.top = canvasRect.top + "px";
  69916. _this._loadingDiv.style.width = canvasRect.width + "px";
  69917. _this._loadingDiv.style.height = canvasRect.height + "px";
  69918. };
  69919. }
  69920. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  69921. if (this._loadingDiv) {
  69922. // Do not add a loading screen if there is already one
  69923. return;
  69924. }
  69925. this._loadingDiv = document.createElement("div");
  69926. this._loadingDiv.id = "babylonjsLoadingDiv";
  69927. this._loadingDiv.style.opacity = "0";
  69928. this._loadingDiv.style.transition = "opacity 1.5s ease";
  69929. this._loadingDiv.style.pointerEvents = "none";
  69930. // Loading text
  69931. this._loadingTextDiv = document.createElement("div");
  69932. this._loadingTextDiv.style.position = "absolute";
  69933. this._loadingTextDiv.style.left = "0";
  69934. this._loadingTextDiv.style.top = "50%";
  69935. this._loadingTextDiv.style.marginTop = "80px";
  69936. this._loadingTextDiv.style.width = "100%";
  69937. this._loadingTextDiv.style.height = "20px";
  69938. this._loadingTextDiv.style.fontFamily = "Arial";
  69939. this._loadingTextDiv.style.fontSize = "14px";
  69940. this._loadingTextDiv.style.color = "white";
  69941. this._loadingTextDiv.style.textAlign = "center";
  69942. this._loadingTextDiv.innerHTML = "Loading";
  69943. this._loadingDiv.appendChild(this._loadingTextDiv);
  69944. //set the predefined text
  69945. this._loadingTextDiv.innerHTML = this._loadingText;
  69946. // Generating keyframes
  69947. var style = document.createElement('style');
  69948. style.type = 'text/css';
  69949. 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 }";
  69950. style.innerHTML = keyFrames;
  69951. document.getElementsByTagName('head')[0].appendChild(style);
  69952. // Loading img
  69953. var imgBack = new Image();
  69954. 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";
  69955. imgBack.style.position = "absolute";
  69956. imgBack.style.left = "50%";
  69957. imgBack.style.top = "50%";
  69958. imgBack.style.marginLeft = "-60px";
  69959. imgBack.style.marginTop = "-60px";
  69960. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  69961. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  69962. imgBack.style.transformOrigin = "50% 50%";
  69963. imgBack.style.webkitTransformOrigin = "50% 50%";
  69964. this._loadingDiv.appendChild(imgBack);
  69965. this._resizeLoadingUI();
  69966. window.addEventListener("resize", this._resizeLoadingUI);
  69967. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69968. document.body.appendChild(this._loadingDiv);
  69969. this._loadingDiv.style.opacity = "1";
  69970. };
  69971. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  69972. var _this = this;
  69973. if (!this._loadingDiv) {
  69974. return;
  69975. }
  69976. var onTransitionEnd = function () {
  69977. if (!_this._loadingDiv) {
  69978. return;
  69979. }
  69980. document.body.removeChild(_this._loadingDiv);
  69981. window.removeEventListener("resize", _this._resizeLoadingUI);
  69982. _this._loadingDiv = null;
  69983. };
  69984. this._loadingDiv.style.opacity = "0";
  69985. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  69986. };
  69987. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  69988. set: function (text) {
  69989. this._loadingText = text;
  69990. if (this._loadingTextDiv) {
  69991. this._loadingTextDiv.innerHTML = this._loadingText;
  69992. }
  69993. },
  69994. enumerable: true,
  69995. configurable: true
  69996. });
  69997. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  69998. get: function () {
  69999. return this._loadingDivBackgroundColor;
  70000. },
  70001. set: function (color) {
  70002. this._loadingDivBackgroundColor = color;
  70003. if (!this._loadingDiv) {
  70004. return;
  70005. }
  70006. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70007. },
  70008. enumerable: true,
  70009. configurable: true
  70010. });
  70011. return DefaultLoadingScreen;
  70012. }());
  70013. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.loadingScreen.js.map
  70016. var BABYLON;
  70017. (function (BABYLON) {
  70018. var SceneLoaderProgressEvent = /** @class */ (function () {
  70019. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70020. this.lengthComputable = lengthComputable;
  70021. this.loaded = loaded;
  70022. this.total = total;
  70023. }
  70024. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70025. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70026. };
  70027. return SceneLoaderProgressEvent;
  70028. }());
  70029. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70030. var SceneLoader = /** @class */ (function () {
  70031. function SceneLoader() {
  70032. }
  70033. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70034. get: function () {
  70035. return 0;
  70036. },
  70037. enumerable: true,
  70038. configurable: true
  70039. });
  70040. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70041. get: function () {
  70042. return 1;
  70043. },
  70044. enumerable: true,
  70045. configurable: true
  70046. });
  70047. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70048. get: function () {
  70049. return 2;
  70050. },
  70051. enumerable: true,
  70052. configurable: true
  70053. });
  70054. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70055. get: function () {
  70056. return 3;
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70062. get: function () {
  70063. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70064. },
  70065. set: function (value) {
  70066. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70067. },
  70068. enumerable: true,
  70069. configurable: true
  70070. });
  70071. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70072. get: function () {
  70073. return SceneLoader._ShowLoadingScreen;
  70074. },
  70075. set: function (value) {
  70076. SceneLoader._ShowLoadingScreen = value;
  70077. },
  70078. enumerable: true,
  70079. configurable: true
  70080. });
  70081. Object.defineProperty(SceneLoader, "loggingLevel", {
  70082. get: function () {
  70083. return SceneLoader._loggingLevel;
  70084. },
  70085. set: function (value) {
  70086. SceneLoader._loggingLevel = value;
  70087. },
  70088. enumerable: true,
  70089. configurable: true
  70090. });
  70091. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70092. get: function () {
  70093. return SceneLoader._CleanBoneMatrixWeights;
  70094. },
  70095. set: function (value) {
  70096. SceneLoader._CleanBoneMatrixWeights = value;
  70097. },
  70098. enumerable: true,
  70099. configurable: true
  70100. });
  70101. SceneLoader._getDefaultPlugin = function () {
  70102. return SceneLoader._registeredPlugins[".babylon"];
  70103. };
  70104. SceneLoader._getPluginForExtension = function (extension) {
  70105. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70106. if (registeredPlugin) {
  70107. return registeredPlugin;
  70108. }
  70109. 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");
  70110. return SceneLoader._getDefaultPlugin();
  70111. };
  70112. SceneLoader._getPluginForDirectLoad = function (data) {
  70113. for (var extension in SceneLoader._registeredPlugins) {
  70114. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70115. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70116. return SceneLoader._registeredPlugins[extension];
  70117. }
  70118. }
  70119. return SceneLoader._getDefaultPlugin();
  70120. };
  70121. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70122. if (sceneFilename.name) {
  70123. sceneFilename = sceneFilename.name;
  70124. }
  70125. var queryStringPosition = sceneFilename.indexOf("?");
  70126. if (queryStringPosition !== -1) {
  70127. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70128. }
  70129. var dotPosition = sceneFilename.lastIndexOf(".");
  70130. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70131. return SceneLoader._getPluginForExtension(extension);
  70132. };
  70133. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70134. SceneLoader._getDirectLoad = function (sceneFilename) {
  70135. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70136. return sceneFilename.substr(5);
  70137. }
  70138. return null;
  70139. };
  70140. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70141. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70142. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70143. var plugin;
  70144. if (registeredPlugin.plugin.createPlugin) {
  70145. plugin = registeredPlugin.plugin.createPlugin();
  70146. }
  70147. else {
  70148. plugin = registeredPlugin.plugin;
  70149. }
  70150. var useArrayBuffer = registeredPlugin.isBinary;
  70151. var database;
  70152. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70153. var dataCallback = function (data, responseURL) {
  70154. if (scene.isDisposed) {
  70155. onError("Scene has been disposed");
  70156. return;
  70157. }
  70158. scene.database = database;
  70159. onSuccess(plugin, data, responseURL);
  70160. };
  70161. var request = null;
  70162. var pluginDisposed = false;
  70163. var onDisposeObservable = plugin.onDisposeObservable;
  70164. if (onDisposeObservable) {
  70165. onDisposeObservable.add(function () {
  70166. pluginDisposed = true;
  70167. if (request) {
  70168. request.abort();
  70169. request = null;
  70170. }
  70171. onDispose();
  70172. });
  70173. }
  70174. var manifestChecked = function () {
  70175. if (pluginDisposed) {
  70176. return;
  70177. }
  70178. var url = rootUrl + sceneFilename;
  70179. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70180. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70181. } : undefined, database, useArrayBuffer, function (request, exception) {
  70182. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70183. });
  70184. };
  70185. if (directLoad) {
  70186. dataCallback(directLoad);
  70187. return plugin;
  70188. }
  70189. if (rootUrl.indexOf("file:") === -1) {
  70190. var engine = scene.getEngine();
  70191. var canUseOfflineSupport = engine.enableOfflineSupport;
  70192. if (canUseOfflineSupport) {
  70193. // Also check for exceptions
  70194. var exceptionFound = false;
  70195. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70196. var regex = _a[_i];
  70197. if (regex.test(rootUrl + sceneFilename)) {
  70198. exceptionFound = true;
  70199. break;
  70200. }
  70201. }
  70202. canUseOfflineSupport = !exceptionFound;
  70203. }
  70204. if (canUseOfflineSupport) {
  70205. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70206. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70207. }
  70208. else {
  70209. manifestChecked();
  70210. }
  70211. }
  70212. // Loading file from disk via input file or drag'n'drop
  70213. else {
  70214. var fileOrString = sceneFilename;
  70215. if (fileOrString.name) { // File
  70216. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70217. }
  70218. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70219. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70220. }
  70221. else {
  70222. onError("Unable to find file named " + sceneFilename);
  70223. }
  70224. }
  70225. return plugin;
  70226. };
  70227. // Public functions
  70228. SceneLoader.GetPluginForExtension = function (extension) {
  70229. return SceneLoader._getPluginForExtension(extension).plugin;
  70230. };
  70231. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70232. return !!SceneLoader._registeredPlugins[extension];
  70233. };
  70234. SceneLoader.RegisterPlugin = function (plugin) {
  70235. if (typeof plugin.extensions === "string") {
  70236. var extension = plugin.extensions;
  70237. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70238. plugin: plugin,
  70239. isBinary: false
  70240. };
  70241. }
  70242. else {
  70243. var extensions = plugin.extensions;
  70244. Object.keys(extensions).forEach(function (extension) {
  70245. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70246. plugin: plugin,
  70247. isBinary: extensions[extension].isBinary
  70248. };
  70249. });
  70250. }
  70251. };
  70252. /**
  70253. * Import meshes into a scene
  70254. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70255. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70256. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70257. * @param scene the instance of BABYLON.Scene to append to
  70258. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70259. * @param onProgress a callback with a progress event for each file being loaded
  70260. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70261. * @param pluginExtension the extension used to determine the plugin
  70262. * @returns The loaded plugin
  70263. */
  70264. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70265. if (sceneFilename === void 0) { sceneFilename = ""; }
  70266. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70267. if (onSuccess === void 0) { onSuccess = null; }
  70268. if (onProgress === void 0) { onProgress = null; }
  70269. if (onError === void 0) { onError = null; }
  70270. if (pluginExtension === void 0) { pluginExtension = null; }
  70271. if (!scene) {
  70272. BABYLON.Tools.Error("No scene available to import mesh to");
  70273. return null;
  70274. }
  70275. if (!sceneFilename) {
  70276. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70277. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70278. }
  70279. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70280. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70281. return null;
  70282. }
  70283. var loadingToken = {};
  70284. scene._addPendingData(loadingToken);
  70285. var disposeHandler = function () {
  70286. scene._removePendingData(loadingToken);
  70287. };
  70288. var errorHandler = function (message, exception) {
  70289. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70290. if (onError) {
  70291. onError(scene, errorMessage, exception);
  70292. }
  70293. else {
  70294. BABYLON.Tools.Error(errorMessage);
  70295. // should the exception be thrown?
  70296. }
  70297. disposeHandler();
  70298. };
  70299. var progressHandler = onProgress ? function (event) {
  70300. try {
  70301. onProgress(event);
  70302. }
  70303. catch (e) {
  70304. errorHandler("Error in onProgress callback", e);
  70305. }
  70306. } : undefined;
  70307. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70308. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70309. if (onSuccess) {
  70310. try {
  70311. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70312. }
  70313. catch (e) {
  70314. errorHandler("Error in onSuccess callback", e);
  70315. }
  70316. }
  70317. scene._removePendingData(loadingToken);
  70318. };
  70319. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70320. if (plugin.rewriteRootURL) {
  70321. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70322. }
  70323. if (sceneFilename === "") {
  70324. if (sceneFilename === "") {
  70325. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70326. }
  70327. }
  70328. if (plugin.importMesh) {
  70329. var syncedPlugin = plugin;
  70330. var meshes = new Array();
  70331. var particleSystems = new Array();
  70332. var skeletons = new Array();
  70333. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70334. return;
  70335. }
  70336. scene.loadingPluginName = plugin.name;
  70337. successHandler(meshes, particleSystems, skeletons, []);
  70338. }
  70339. else {
  70340. var asyncedPlugin = plugin;
  70341. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70342. scene.loadingPluginName = plugin.name;
  70343. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70344. }).catch(function (error) {
  70345. errorHandler(error.message, error);
  70346. });
  70347. }
  70348. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70349. };
  70350. /**
  70351. * Import meshes into a scene
  70352. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70353. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70354. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70355. * @param scene the instance of BABYLON.Scene to append to
  70356. * @param onProgress a callback with a progress event for each file being loaded
  70357. * @param pluginExtension the extension used to determine the plugin
  70358. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70359. */
  70360. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70361. if (sceneFilename === void 0) { sceneFilename = ""; }
  70362. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70363. if (onProgress === void 0) { onProgress = null; }
  70364. if (pluginExtension === void 0) { pluginExtension = null; }
  70365. return new Promise(function (resolve, reject) {
  70366. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70367. resolve({
  70368. meshes: meshes,
  70369. particleSystems: particleSystems,
  70370. skeletons: skeletons,
  70371. animationGroups: animationGroups
  70372. });
  70373. }, onProgress, function (scene, message, exception) {
  70374. reject(exception || new Error(message));
  70375. }, pluginExtension);
  70376. });
  70377. };
  70378. /**
  70379. * Load a scene
  70380. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70381. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70382. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70383. * @param onSuccess a callback with the scene when import succeeds
  70384. * @param onProgress a callback with a progress event for each file being loaded
  70385. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70386. * @param pluginExtension the extension used to determine the plugin
  70387. * @returns The loaded plugin
  70388. */
  70389. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70390. if (onSuccess === void 0) { onSuccess = null; }
  70391. if (onProgress === void 0) { onProgress = null; }
  70392. if (onError === void 0) { onError = null; }
  70393. if (pluginExtension === void 0) { pluginExtension = null; }
  70394. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70395. };
  70396. /**
  70397. * Load a scene
  70398. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70399. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70400. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70401. * @param onProgress a callback with a progress event for each file being loaded
  70402. * @param pluginExtension the extension used to determine the plugin
  70403. * @returns The loaded scene
  70404. */
  70405. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70406. if (onProgress === void 0) { onProgress = null; }
  70407. if (pluginExtension === void 0) { pluginExtension = null; }
  70408. return new Promise(function (resolve, reject) {
  70409. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70410. resolve(scene);
  70411. }, onProgress, function (scene, message, exception) {
  70412. reject(exception || new Error(message));
  70413. }, pluginExtension);
  70414. });
  70415. };
  70416. /**
  70417. * Append a scene
  70418. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70419. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70420. * @param scene is the instance of BABYLON.Scene to append to
  70421. * @param onSuccess a callback with the scene when import succeeds
  70422. * @param onProgress a callback with a progress event for each file being loaded
  70423. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70424. * @param pluginExtension the extension used to determine the plugin
  70425. * @returns The loaded plugin
  70426. */
  70427. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70428. if (sceneFilename === void 0) { sceneFilename = ""; }
  70429. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70430. if (onSuccess === void 0) { onSuccess = null; }
  70431. if (onProgress === void 0) { onProgress = null; }
  70432. if (onError === void 0) { onError = null; }
  70433. if (pluginExtension === void 0) { pluginExtension = null; }
  70434. if (!scene) {
  70435. BABYLON.Tools.Error("No scene available to append to");
  70436. return null;
  70437. }
  70438. if (!sceneFilename) {
  70439. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70440. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70441. }
  70442. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70443. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70444. return null;
  70445. }
  70446. if (SceneLoader.ShowLoadingScreen) {
  70447. scene.getEngine().displayLoadingUI();
  70448. }
  70449. var loadingToken = {};
  70450. scene._addPendingData(loadingToken);
  70451. var disposeHandler = function () {
  70452. scene._removePendingData(loadingToken);
  70453. scene.getEngine().hideLoadingUI();
  70454. };
  70455. var errorHandler = function (message, exception) {
  70456. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70457. if (onError) {
  70458. onError(scene, errorMessage, exception);
  70459. }
  70460. else {
  70461. BABYLON.Tools.Error(errorMessage);
  70462. // should the exception be thrown?
  70463. }
  70464. disposeHandler();
  70465. };
  70466. var progressHandler = onProgress ? function (event) {
  70467. try {
  70468. onProgress(event);
  70469. }
  70470. catch (e) {
  70471. errorHandler("Error in onProgress callback", e);
  70472. }
  70473. } : undefined;
  70474. var successHandler = function () {
  70475. if (onSuccess) {
  70476. try {
  70477. onSuccess(scene);
  70478. }
  70479. catch (e) {
  70480. errorHandler("Error in onSuccess callback", e);
  70481. }
  70482. }
  70483. scene._removePendingData(loadingToken);
  70484. };
  70485. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70486. if (sceneFilename === "") {
  70487. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70488. }
  70489. if (plugin.load) {
  70490. var syncedPlugin = plugin;
  70491. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70492. return;
  70493. }
  70494. scene.loadingPluginName = plugin.name;
  70495. successHandler();
  70496. }
  70497. else {
  70498. var asyncedPlugin = plugin;
  70499. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70500. scene.loadingPluginName = plugin.name;
  70501. successHandler();
  70502. }).catch(function (error) {
  70503. errorHandler(error.message, error);
  70504. });
  70505. }
  70506. if (SceneLoader.ShowLoadingScreen) {
  70507. scene.executeWhenReady(function () {
  70508. scene.getEngine().hideLoadingUI();
  70509. });
  70510. }
  70511. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70512. };
  70513. /**
  70514. * Append a scene
  70515. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70516. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70517. * @param scene is the instance of BABYLON.Scene to append to
  70518. * @param onProgress a callback with a progress event for each file being loaded
  70519. * @param pluginExtension the extension used to determine the plugin
  70520. * @returns The given scene
  70521. */
  70522. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70523. if (sceneFilename === void 0) { sceneFilename = ""; }
  70524. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70525. if (onProgress === void 0) { onProgress = null; }
  70526. if (pluginExtension === void 0) { pluginExtension = null; }
  70527. return new Promise(function (resolve, reject) {
  70528. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70529. resolve(scene);
  70530. }, onProgress, function (scene, message, exception) {
  70531. reject(exception || new Error(message));
  70532. }, pluginExtension);
  70533. });
  70534. };
  70535. /**
  70536. * Load a scene into an asset container
  70537. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70538. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70539. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70540. * @param onSuccess a callback with the scene when import succeeds
  70541. * @param onProgress a callback with a progress event for each file being loaded
  70542. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70543. * @param pluginExtension the extension used to determine the plugin
  70544. * @returns The loaded plugin
  70545. */
  70546. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70547. if (sceneFilename === void 0) { sceneFilename = ""; }
  70548. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70549. if (onSuccess === void 0) { onSuccess = null; }
  70550. if (onProgress === void 0) { onProgress = null; }
  70551. if (onError === void 0) { onError = null; }
  70552. if (pluginExtension === void 0) { pluginExtension = null; }
  70553. if (!scene) {
  70554. BABYLON.Tools.Error("No scene available to load asset container to");
  70555. return null;
  70556. }
  70557. if (!sceneFilename) {
  70558. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70559. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70560. }
  70561. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70562. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70563. return null;
  70564. }
  70565. var loadingToken = {};
  70566. scene._addPendingData(loadingToken);
  70567. var disposeHandler = function () {
  70568. scene._removePendingData(loadingToken);
  70569. };
  70570. var errorHandler = function (message, exception) {
  70571. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70572. if (onError) {
  70573. onError(scene, errorMessage, exception);
  70574. }
  70575. else {
  70576. BABYLON.Tools.Error(errorMessage);
  70577. // should the exception be thrown?
  70578. }
  70579. disposeHandler();
  70580. };
  70581. var progressHandler = onProgress ? function (event) {
  70582. try {
  70583. onProgress(event);
  70584. }
  70585. catch (e) {
  70586. errorHandler("Error in onProgress callback", e);
  70587. }
  70588. } : undefined;
  70589. var successHandler = function (assets) {
  70590. if (onSuccess) {
  70591. try {
  70592. onSuccess(assets);
  70593. }
  70594. catch (e) {
  70595. errorHandler("Error in onSuccess callback", e);
  70596. }
  70597. }
  70598. scene._removePendingData(loadingToken);
  70599. };
  70600. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70601. if (plugin.loadAssetContainer) {
  70602. var syncedPlugin = plugin;
  70603. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70604. if (!assetContainer) {
  70605. return;
  70606. }
  70607. scene.loadingPluginName = plugin.name;
  70608. successHandler(assetContainer);
  70609. }
  70610. else if (plugin.loadAssetContainerAsync) {
  70611. var asyncedPlugin = plugin;
  70612. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70613. scene.loadingPluginName = plugin.name;
  70614. successHandler(assetContainer);
  70615. }).catch(function (error) {
  70616. errorHandler(error.message, error);
  70617. });
  70618. }
  70619. else {
  70620. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70621. }
  70622. if (SceneLoader.ShowLoadingScreen) {
  70623. scene.executeWhenReady(function () {
  70624. scene.getEngine().hideLoadingUI();
  70625. });
  70626. }
  70627. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70628. };
  70629. /**
  70630. * Load a scene into an asset container
  70631. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70632. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70633. * @param scene is the instance of BABYLON.Scene to append to
  70634. * @param onProgress a callback with a progress event for each file being loaded
  70635. * @param pluginExtension the extension used to determine the plugin
  70636. * @returns The loaded asset container
  70637. */
  70638. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70639. if (sceneFilename === void 0) { sceneFilename = ""; }
  70640. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70641. if (onProgress === void 0) { onProgress = null; }
  70642. if (pluginExtension === void 0) { pluginExtension = null; }
  70643. return new Promise(function (resolve, reject) {
  70644. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70645. resolve(assetContainer);
  70646. }, onProgress, function (scene, message, exception) {
  70647. reject(exception || new Error(message));
  70648. }, pluginExtension);
  70649. });
  70650. };
  70651. // Flags
  70652. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70653. SceneLoader._ShowLoadingScreen = true;
  70654. SceneLoader._CleanBoneMatrixWeights = false;
  70655. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70656. // Members
  70657. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70658. SceneLoader._registeredPlugins = {};
  70659. return SceneLoader;
  70660. }());
  70661. BABYLON.SceneLoader = SceneLoader;
  70662. ;
  70663. })(BABYLON || (BABYLON = {}));
  70664. //# sourceMappingURL=babylon.sceneLoader.js.map
  70665. var BABYLON;
  70666. (function (BABYLON) {
  70667. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70668. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70669. var parsedMaterial = parsedData.materials[index];
  70670. if (parsedMaterial.id === id) {
  70671. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70672. }
  70673. }
  70674. return null;
  70675. };
  70676. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70677. for (var i in names) {
  70678. if (mesh.name === names[i]) {
  70679. hierarchyIds.push(mesh.id);
  70680. return true;
  70681. }
  70682. }
  70683. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70684. hierarchyIds.push(mesh.id);
  70685. return true;
  70686. }
  70687. return false;
  70688. };
  70689. var logOperation = function (operation, producer) {
  70690. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70691. };
  70692. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70693. if (addToScene === void 0) { addToScene = false; }
  70694. var container = new BABYLON.AssetContainer(scene);
  70695. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70696. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70697. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70698. // and avoid problems with multiple concurrent .babylon loads.
  70699. var log = "importScene has failed JSON parse";
  70700. try {
  70701. var parsedData = JSON.parse(data);
  70702. log = "";
  70703. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70704. var index;
  70705. var cache;
  70706. // Lights
  70707. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70708. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70709. var parsedLight = parsedData.lights[index];
  70710. var light = BABYLON.Light.Parse(parsedLight, scene);
  70711. if (light) {
  70712. container.lights.push(light);
  70713. log += (index === 0 ? "\n\tLights:" : "");
  70714. log += "\n\t\t" + light.toString(fullDetails);
  70715. }
  70716. }
  70717. }
  70718. // Animations
  70719. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  70720. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  70721. var parsedAnimation = parsedData.animations[index];
  70722. var animation = BABYLON.Animation.Parse(parsedAnimation);
  70723. scene.animations.push(animation);
  70724. container.animations.push(animation);
  70725. log += (index === 0 ? "\n\tAnimations:" : "");
  70726. log += "\n\t\t" + animation.toString(fullDetails);
  70727. }
  70728. }
  70729. // Materials
  70730. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  70731. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70732. var parsedMaterial = parsedData.materials[index];
  70733. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70734. container.materials.push(mat);
  70735. log += (index === 0 ? "\n\tMaterials:" : "");
  70736. log += "\n\t\t" + mat.toString(fullDetails);
  70737. }
  70738. }
  70739. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70740. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  70741. var parsedMultiMaterial = parsedData.multiMaterials[index];
  70742. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70743. container.multiMaterials.push(mmat);
  70744. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  70745. log += "\n\t\t" + mmat.toString(fullDetails);
  70746. }
  70747. }
  70748. // Morph targets
  70749. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70750. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70751. var managerData = _a[_i];
  70752. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  70753. }
  70754. }
  70755. // Skeletons
  70756. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70757. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70758. var parsedSkeleton = parsedData.skeletons[index];
  70759. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70760. container.skeletons.push(skeleton);
  70761. log += (index === 0 ? "\n\tSkeletons:" : "");
  70762. log += "\n\t\t" + skeleton.toString(fullDetails);
  70763. }
  70764. }
  70765. // Geometries
  70766. var geometries = parsedData.geometries;
  70767. if (geometries !== undefined && geometries !== null) {
  70768. var addedGeometry = new Array();
  70769. // Boxes
  70770. var boxes = geometries.boxes;
  70771. if (boxes !== undefined && boxes !== null) {
  70772. for (index = 0, cache = boxes.length; index < cache; index++) {
  70773. var parsedBox = boxes[index];
  70774. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  70775. }
  70776. }
  70777. // Spheres
  70778. var spheres = geometries.spheres;
  70779. if (spheres !== undefined && spheres !== null) {
  70780. for (index = 0, cache = spheres.length; index < cache; index++) {
  70781. var parsedSphere = spheres[index];
  70782. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  70783. }
  70784. }
  70785. // Cylinders
  70786. var cylinders = geometries.cylinders;
  70787. if (cylinders !== undefined && cylinders !== null) {
  70788. for (index = 0, cache = cylinders.length; index < cache; index++) {
  70789. var parsedCylinder = cylinders[index];
  70790. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  70791. }
  70792. }
  70793. // Toruses
  70794. var toruses = geometries.toruses;
  70795. if (toruses !== undefined && toruses !== null) {
  70796. for (index = 0, cache = toruses.length; index < cache; index++) {
  70797. var parsedTorus = toruses[index];
  70798. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  70799. }
  70800. }
  70801. // Grounds
  70802. var grounds = geometries.grounds;
  70803. if (grounds !== undefined && grounds !== null) {
  70804. for (index = 0, cache = grounds.length; index < cache; index++) {
  70805. var parsedGround = grounds[index];
  70806. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  70807. }
  70808. }
  70809. // Planes
  70810. var planes = geometries.planes;
  70811. if (planes !== undefined && planes !== null) {
  70812. for (index = 0, cache = planes.length; index < cache; index++) {
  70813. var parsedPlane = planes[index];
  70814. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  70815. }
  70816. }
  70817. // TorusKnots
  70818. var torusKnots = geometries.torusKnots;
  70819. if (torusKnots !== undefined && torusKnots !== null) {
  70820. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  70821. var parsedTorusKnot = torusKnots[index];
  70822. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  70823. }
  70824. }
  70825. // VertexData
  70826. var vertexData = geometries.vertexData;
  70827. if (vertexData !== undefined && vertexData !== null) {
  70828. for (index = 0, cache = vertexData.length; index < cache; index++) {
  70829. var parsedVertexData = vertexData[index];
  70830. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  70831. }
  70832. }
  70833. addedGeometry.forEach(function (g) {
  70834. if (g) {
  70835. container.geometries.push(g);
  70836. }
  70837. });
  70838. }
  70839. // Transform nodes
  70840. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  70841. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  70842. var parsedTransformNode = parsedData.transformNodes[index];
  70843. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  70844. container.transformNodes.push(node);
  70845. }
  70846. }
  70847. // Meshes
  70848. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70849. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70850. var parsedMesh = parsedData.meshes[index];
  70851. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70852. container.meshes.push(mesh);
  70853. log += (index === 0 ? "\n\tMeshes:" : "");
  70854. log += "\n\t\t" + mesh.toString(fullDetails);
  70855. }
  70856. }
  70857. // Cameras
  70858. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  70859. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  70860. var parsedCamera = parsedData.cameras[index];
  70861. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  70862. container.cameras.push(camera);
  70863. log += (index === 0 ? "\n\tCameras:" : "");
  70864. log += "\n\t\t" + camera.toString(fullDetails);
  70865. }
  70866. }
  70867. // Browsing all the graph to connect the dots
  70868. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  70869. var camera = scene.cameras[index];
  70870. if (camera._waitingParentId) {
  70871. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  70872. camera._waitingParentId = null;
  70873. }
  70874. }
  70875. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70876. var light_1 = scene.lights[index];
  70877. if (light_1 && light_1._waitingParentId) {
  70878. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  70879. light_1._waitingParentId = null;
  70880. }
  70881. }
  70882. // Sounds
  70883. // TODO: add sound
  70884. var loadedSounds = [];
  70885. var loadedSound;
  70886. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70887. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70888. var parsedSound = parsedData.sounds[index];
  70889. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70890. if (!parsedSound.url)
  70891. parsedSound.url = parsedSound.name;
  70892. if (!loadedSounds[parsedSound.url]) {
  70893. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70894. loadedSounds[parsedSound.url] = loadedSound;
  70895. container.sounds.push(loadedSound);
  70896. }
  70897. else {
  70898. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70899. }
  70900. }
  70901. else {
  70902. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70903. }
  70904. }
  70905. }
  70906. loadedSounds = [];
  70907. // Connect parents & children and parse actions
  70908. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  70909. var transformNode = scene.transformNodes[index];
  70910. if (transformNode._waitingParentId) {
  70911. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  70912. transformNode._waitingParentId = null;
  70913. }
  70914. }
  70915. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70916. var mesh = scene.meshes[index];
  70917. if (mesh._waitingParentId) {
  70918. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  70919. mesh._waitingParentId = null;
  70920. }
  70921. if (mesh._waitingActions) {
  70922. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  70923. mesh._waitingActions = null;
  70924. }
  70925. }
  70926. // freeze world matrix application
  70927. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70928. var currentMesh = scene.meshes[index];
  70929. if (currentMesh._waitingFreezeWorldMatrix) {
  70930. currentMesh.freezeWorldMatrix();
  70931. currentMesh._waitingFreezeWorldMatrix = null;
  70932. }
  70933. else {
  70934. currentMesh.computeWorldMatrix(true);
  70935. }
  70936. }
  70937. // Shadows
  70938. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70939. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70940. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70941. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70942. // SG would be available on their associated lights
  70943. }
  70944. }
  70945. // Lights exclusions / inclusions
  70946. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70947. var light_2 = scene.lights[index];
  70948. // Excluded check
  70949. if (light_2._excludedMeshesIds.length > 0) {
  70950. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  70951. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  70952. if (excludedMesh) {
  70953. light_2.excludedMeshes.push(excludedMesh);
  70954. }
  70955. }
  70956. light_2._excludedMeshesIds = [];
  70957. }
  70958. // Included check
  70959. if (light_2._includedOnlyMeshesIds.length > 0) {
  70960. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  70961. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  70962. if (includedOnlyMesh) {
  70963. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  70964. }
  70965. }
  70966. light_2._includedOnlyMeshesIds = [];
  70967. }
  70968. }
  70969. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  70970. // Actions (scene)
  70971. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  70972. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  70973. }
  70974. if (!addToScene) {
  70975. container.removeAllFromScene();
  70976. }
  70977. }
  70978. catch (err) {
  70979. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  70980. if (onError) {
  70981. onError(msg, err);
  70982. }
  70983. else {
  70984. BABYLON.Tools.Log(msg);
  70985. throw err;
  70986. }
  70987. }
  70988. finally {
  70989. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70990. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70991. }
  70992. }
  70993. return container;
  70994. };
  70995. BABYLON.SceneLoader.RegisterPlugin({
  70996. name: "babylon.js",
  70997. extensions: ".babylon",
  70998. canDirectLoad: function (data) {
  70999. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71000. return true;
  71001. }
  71002. return false;
  71003. },
  71004. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71005. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71006. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71007. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71008. // and avoid problems with multiple concurrent .babylon loads.
  71009. var log = "importMesh has failed JSON parse";
  71010. try {
  71011. var parsedData = JSON.parse(data);
  71012. log = "";
  71013. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71014. if (!meshesNames) {
  71015. meshesNames = null;
  71016. }
  71017. else if (!Array.isArray(meshesNames)) {
  71018. meshesNames = [meshesNames];
  71019. }
  71020. var hierarchyIds = new Array();
  71021. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71022. var loadedSkeletonsIds = [];
  71023. var loadedMaterialsIds = [];
  71024. var index;
  71025. var cache;
  71026. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71027. var parsedMesh = parsedData.meshes[index];
  71028. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71029. if (meshesNames !== null) {
  71030. // Remove found mesh name from list.
  71031. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71032. }
  71033. //Geometry?
  71034. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71035. //does the file contain geometries?
  71036. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71037. //find the correct geometry and add it to the scene
  71038. var found = false;
  71039. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71040. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71041. return;
  71042. }
  71043. else {
  71044. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71045. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71046. switch (geometryType) {
  71047. case "boxes":
  71048. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71049. break;
  71050. case "spheres":
  71051. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71052. break;
  71053. case "cylinders":
  71054. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71055. break;
  71056. case "toruses":
  71057. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71058. break;
  71059. case "grounds":
  71060. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71061. break;
  71062. case "planes":
  71063. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71064. break;
  71065. case "torusKnots":
  71066. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71067. break;
  71068. case "vertexData":
  71069. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71070. break;
  71071. }
  71072. found = true;
  71073. }
  71074. });
  71075. }
  71076. });
  71077. if (found === false) {
  71078. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71079. }
  71080. }
  71081. }
  71082. // Material ?
  71083. if (parsedMesh.materialId) {
  71084. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71085. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71086. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71087. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71088. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71089. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71090. var subMatId = parsedMultiMaterial.materials[matIndex];
  71091. loadedMaterialsIds.push(subMatId);
  71092. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71093. if (mat) {
  71094. log += "\n\tMaterial " + mat.toString(fullDetails);
  71095. }
  71096. }
  71097. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71098. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71099. if (mmat) {
  71100. materialFound = true;
  71101. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71102. }
  71103. break;
  71104. }
  71105. }
  71106. }
  71107. if (materialFound === false) {
  71108. loadedMaterialsIds.push(parsedMesh.materialId);
  71109. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71110. if (!mat) {
  71111. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71112. }
  71113. else {
  71114. log += "\n\tMaterial " + mat.toString(fullDetails);
  71115. }
  71116. }
  71117. }
  71118. // Skeleton ?
  71119. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71120. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71121. if (skeletonAlreadyLoaded === false) {
  71122. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71123. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71124. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71125. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71126. skeletons.push(skeleton);
  71127. loadedSkeletonsIds.push(parsedSkeleton.id);
  71128. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71129. }
  71130. }
  71131. }
  71132. }
  71133. // Morph targets ?
  71134. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71135. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71136. var managerData = _a[_i];
  71137. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71138. }
  71139. }
  71140. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71141. meshes.push(mesh);
  71142. log += "\n\tMesh " + mesh.toString(fullDetails);
  71143. }
  71144. }
  71145. // Connecting parents
  71146. var currentMesh;
  71147. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71148. currentMesh = scene.meshes[index];
  71149. if (currentMesh._waitingParentId) {
  71150. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71151. currentMesh._waitingParentId = null;
  71152. }
  71153. }
  71154. // freeze and compute world matrix application
  71155. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71156. currentMesh = scene.meshes[index];
  71157. if (currentMesh._waitingFreezeWorldMatrix) {
  71158. currentMesh.freezeWorldMatrix();
  71159. currentMesh._waitingFreezeWorldMatrix = null;
  71160. }
  71161. else {
  71162. currentMesh.computeWorldMatrix(true);
  71163. }
  71164. }
  71165. }
  71166. // Particles
  71167. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71168. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71169. if (parser) {
  71170. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71171. var parsedParticleSystem = parsedData.particleSystems[index];
  71172. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71173. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71174. }
  71175. }
  71176. }
  71177. }
  71178. return true;
  71179. }
  71180. catch (err) {
  71181. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71182. if (onError) {
  71183. onError(msg, err);
  71184. }
  71185. else {
  71186. BABYLON.Tools.Log(msg);
  71187. throw err;
  71188. }
  71189. }
  71190. finally {
  71191. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71192. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71193. }
  71194. }
  71195. return false;
  71196. },
  71197. load: function (scene, data, rootUrl, onError) {
  71198. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71199. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71200. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71201. // and avoid problems with multiple concurrent .babylon loads.
  71202. var log = "importScene has failed JSON parse";
  71203. try {
  71204. var parsedData = JSON.parse(data);
  71205. log = "";
  71206. // Scene
  71207. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71208. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71209. }
  71210. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71211. scene.autoClear = parsedData.autoClear;
  71212. }
  71213. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71214. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71215. }
  71216. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71217. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71218. }
  71219. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71220. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71221. }
  71222. // Fog
  71223. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71224. scene.fogMode = parsedData.fogMode;
  71225. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71226. scene.fogStart = parsedData.fogStart;
  71227. scene.fogEnd = parsedData.fogEnd;
  71228. scene.fogDensity = parsedData.fogDensity;
  71229. log += "\tFog mode for scene: ";
  71230. switch (scene.fogMode) {
  71231. // getters not compiling, so using hardcoded
  71232. case 1:
  71233. log += "exp\n";
  71234. break;
  71235. case 2:
  71236. log += "exp2\n";
  71237. break;
  71238. case 3:
  71239. log += "linear\n";
  71240. break;
  71241. }
  71242. }
  71243. //Physics
  71244. if (parsedData.physicsEnabled) {
  71245. var physicsPlugin;
  71246. if (parsedData.physicsEngine === "cannon") {
  71247. physicsPlugin = new BABYLON.CannonJSPlugin();
  71248. }
  71249. else if (parsedData.physicsEngine === "oimo") {
  71250. physicsPlugin = new BABYLON.OimoJSPlugin();
  71251. }
  71252. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71253. //else - default engine, which is currently oimo
  71254. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71255. scene.enablePhysics(physicsGravity, physicsPlugin);
  71256. }
  71257. // Metadata
  71258. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71259. scene.metadata = parsedData.metadata;
  71260. }
  71261. //collisions, if defined. otherwise, default is true
  71262. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71263. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71264. }
  71265. scene.workerCollisions = !!parsedData.workerCollisions;
  71266. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71267. if (!container) {
  71268. return false;
  71269. }
  71270. if (parsedData.autoAnimate) {
  71271. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71272. }
  71273. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71274. scene.setActiveCameraByID(parsedData.activeCameraID);
  71275. }
  71276. // Environment texture
  71277. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71278. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71279. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71280. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71281. if (parsedData.environmentTextureRotationY) {
  71282. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71283. }
  71284. scene.environmentTexture = hdrTexture;
  71285. }
  71286. else {
  71287. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71288. if (parsedData.environmentTextureRotationY) {
  71289. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71290. }
  71291. scene.environmentTexture = cubeTexture;
  71292. }
  71293. if (parsedData.createDefaultSkybox === true) {
  71294. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71295. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71296. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71297. }
  71298. }
  71299. // Finish
  71300. return true;
  71301. }
  71302. catch (err) {
  71303. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71304. if (onError) {
  71305. onError(msg, err);
  71306. }
  71307. else {
  71308. BABYLON.Tools.Log(msg);
  71309. throw err;
  71310. }
  71311. }
  71312. finally {
  71313. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71314. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71315. }
  71316. }
  71317. return false;
  71318. },
  71319. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71320. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71321. return container;
  71322. }
  71323. });
  71324. })(BABYLON || (BABYLON = {}));
  71325. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71326. var BABYLON;
  71327. (function (BABYLON) {
  71328. var FilesInput = /** @class */ (function () {
  71329. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71330. this.onProcessFileCallback = function () { return true; };
  71331. this._engine = engine;
  71332. this._currentScene = scene;
  71333. this._sceneLoadedCallback = sceneLoadedCallback;
  71334. this._progressCallback = progressCallback;
  71335. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71336. this._textureLoadingCallback = textureLoadingCallback;
  71337. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71338. this._onReloadCallback = onReloadCallback;
  71339. this._errorCallback = errorCallback;
  71340. }
  71341. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71342. var _this = this;
  71343. if (elementToMonitor) {
  71344. this._elementToMonitor = elementToMonitor;
  71345. this._dragEnterHandler = function (e) { _this.drag(e); };
  71346. this._dragOverHandler = function (e) { _this.drag(e); };
  71347. this._dropHandler = function (e) { _this.drop(e); };
  71348. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71349. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71350. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71351. }
  71352. };
  71353. FilesInput.prototype.dispose = function () {
  71354. if (!this._elementToMonitor) {
  71355. return;
  71356. }
  71357. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71358. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71359. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71360. };
  71361. FilesInput.prototype.renderFunction = function () {
  71362. if (this._additionalRenderLoopLogicCallback) {
  71363. this._additionalRenderLoopLogicCallback();
  71364. }
  71365. if (this._currentScene) {
  71366. if (this._textureLoadingCallback) {
  71367. var remaining = this._currentScene.getWaitingItemsCount();
  71368. if (remaining > 0) {
  71369. this._textureLoadingCallback(remaining);
  71370. }
  71371. }
  71372. this._currentScene.render();
  71373. }
  71374. };
  71375. FilesInput.prototype.drag = function (e) {
  71376. e.stopPropagation();
  71377. e.preventDefault();
  71378. };
  71379. FilesInput.prototype.drop = function (eventDrop) {
  71380. eventDrop.stopPropagation();
  71381. eventDrop.preventDefault();
  71382. this.loadFiles(eventDrop);
  71383. };
  71384. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71385. var _this = this;
  71386. var reader = folder.createReader();
  71387. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71388. reader.readEntries(function (entries) {
  71389. remaining.count += entries.length;
  71390. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71391. var entry = entries_1[_i];
  71392. if (entry.isFile) {
  71393. entry.file(function (file) {
  71394. file.correctName = relativePath + file.name;
  71395. files.push(file);
  71396. if (--remaining.count === 0) {
  71397. callback();
  71398. }
  71399. });
  71400. }
  71401. else if (entry.isDirectory) {
  71402. _this._traverseFolder(entry, files, remaining, callback);
  71403. }
  71404. }
  71405. if (--remaining.count) {
  71406. callback();
  71407. }
  71408. });
  71409. };
  71410. FilesInput.prototype._processFiles = function (files) {
  71411. for (var i = 0; i < files.length; i++) {
  71412. var name = files[i].correctName.toLowerCase();
  71413. var extension = name.split('.').pop();
  71414. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71415. continue;
  71416. }
  71417. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71418. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71419. this._sceneFileToLoad = files[i];
  71420. }
  71421. else {
  71422. FilesInput.FilesToLoad[name] = files[i];
  71423. }
  71424. }
  71425. };
  71426. FilesInput.prototype.loadFiles = function (event) {
  71427. var _this = this;
  71428. if (this._startingProcessingFilesCallback)
  71429. this._startingProcessingFilesCallback();
  71430. // Handling data transfer via drag'n'drop
  71431. if (event && event.dataTransfer && event.dataTransfer.files) {
  71432. this._filesToLoad = event.dataTransfer.files;
  71433. }
  71434. // Handling files from input files
  71435. if (event && event.target && event.target.files) {
  71436. this._filesToLoad = event.target.files;
  71437. }
  71438. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71439. var files_1 = new Array();
  71440. var folders = [];
  71441. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71442. for (var i = 0; i < this._filesToLoad.length; i++) {
  71443. var fileToLoad = this._filesToLoad[i];
  71444. var name_1 = fileToLoad.name.toLowerCase();
  71445. var entry = void 0;
  71446. fileToLoad.correctName = name_1;
  71447. if (items) {
  71448. var item = items[i];
  71449. if (item.getAsEntry) {
  71450. entry = item.getAsEntry();
  71451. }
  71452. else if (item.webkitGetAsEntry) {
  71453. entry = item.webkitGetAsEntry();
  71454. }
  71455. }
  71456. if (!entry) {
  71457. files_1.push(fileToLoad);
  71458. }
  71459. else {
  71460. if (entry.isDirectory) {
  71461. folders.push(entry);
  71462. }
  71463. else {
  71464. files_1.push(fileToLoad);
  71465. }
  71466. }
  71467. }
  71468. if (folders.length === 0) {
  71469. this._processFiles(files_1);
  71470. this._processReload();
  71471. }
  71472. else {
  71473. var remaining = { count: folders.length };
  71474. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71475. var folder = folders_1[_i];
  71476. this._traverseFolder(folder, files_1, remaining, function () {
  71477. _this._processFiles(files_1);
  71478. if (remaining.count === 0) {
  71479. _this._processReload();
  71480. }
  71481. });
  71482. }
  71483. }
  71484. }
  71485. };
  71486. FilesInput.prototype._processReload = function () {
  71487. if (this._onReloadCallback) {
  71488. this._onReloadCallback(this._sceneFileToLoad);
  71489. }
  71490. else {
  71491. this.reload();
  71492. }
  71493. };
  71494. FilesInput.prototype.reload = function () {
  71495. var _this = this;
  71496. // If a scene file has been provided
  71497. if (this._sceneFileToLoad) {
  71498. if (this._currentScene) {
  71499. if (BABYLON.Tools.errorsCount > 0) {
  71500. BABYLON.Tools.ClearLogCache();
  71501. }
  71502. this._engine.stopRenderLoop();
  71503. }
  71504. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71505. if (_this._progressCallback) {
  71506. _this._progressCallback(progress);
  71507. }
  71508. }).then(function (scene) {
  71509. if (_this._currentScene) {
  71510. _this._currentScene.dispose();
  71511. }
  71512. _this._currentScene = scene;
  71513. if (_this._sceneLoadedCallback) {
  71514. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71515. }
  71516. // Wait for textures and shaders to be ready
  71517. _this._currentScene.executeWhenReady(function () {
  71518. _this._engine.runRenderLoop(function () {
  71519. _this.renderFunction();
  71520. });
  71521. });
  71522. }).catch(function (error) {
  71523. if (_this._errorCallback) {
  71524. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71525. }
  71526. });
  71527. }
  71528. else {
  71529. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71530. }
  71531. };
  71532. FilesInput.FilesToLoad = {};
  71533. return FilesInput;
  71534. }());
  71535. BABYLON.FilesInput = FilesInput;
  71536. })(BABYLON || (BABYLON = {}));
  71537. //# sourceMappingURL=babylon.filesInput.js.map
  71538. var BABYLON;
  71539. (function (BABYLON) {
  71540. var Tags = /** @class */ (function () {
  71541. function Tags() {
  71542. }
  71543. Tags.EnableFor = function (obj) {
  71544. obj._tags = obj._tags || {};
  71545. obj.hasTags = function () {
  71546. return Tags.HasTags(obj);
  71547. };
  71548. obj.addTags = function (tagsString) {
  71549. return Tags.AddTagsTo(obj, tagsString);
  71550. };
  71551. obj.removeTags = function (tagsString) {
  71552. return Tags.RemoveTagsFrom(obj, tagsString);
  71553. };
  71554. obj.matchesTagsQuery = function (tagsQuery) {
  71555. return Tags.MatchesQuery(obj, tagsQuery);
  71556. };
  71557. };
  71558. Tags.DisableFor = function (obj) {
  71559. delete obj._tags;
  71560. delete obj.hasTags;
  71561. delete obj.addTags;
  71562. delete obj.removeTags;
  71563. delete obj.matchesTagsQuery;
  71564. };
  71565. Tags.HasTags = function (obj) {
  71566. if (!obj._tags) {
  71567. return false;
  71568. }
  71569. return !BABYLON.Tools.IsEmpty(obj._tags);
  71570. };
  71571. Tags.GetTags = function (obj, asString) {
  71572. if (asString === void 0) { asString = true; }
  71573. if (!obj._tags) {
  71574. return null;
  71575. }
  71576. if (asString) {
  71577. var tagsArray = [];
  71578. for (var tag in obj._tags) {
  71579. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71580. tagsArray.push(tag);
  71581. }
  71582. }
  71583. return tagsArray.join(" ");
  71584. }
  71585. else {
  71586. return obj._tags;
  71587. }
  71588. };
  71589. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71590. // a tag cannot start with '||', '&&', and '!'
  71591. // it cannot contain whitespaces
  71592. Tags.AddTagsTo = function (obj, tagsString) {
  71593. if (!tagsString) {
  71594. return;
  71595. }
  71596. if (typeof tagsString !== "string") {
  71597. return;
  71598. }
  71599. var tags = tagsString.split(" ");
  71600. tags.forEach(function (tag, index, array) {
  71601. Tags._AddTagTo(obj, tag);
  71602. });
  71603. };
  71604. Tags._AddTagTo = function (obj, tag) {
  71605. tag = tag.trim();
  71606. if (tag === "" || tag === "true" || tag === "false") {
  71607. return;
  71608. }
  71609. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71610. return;
  71611. }
  71612. Tags.EnableFor(obj);
  71613. obj._tags[tag] = true;
  71614. };
  71615. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71616. if (!Tags.HasTags(obj)) {
  71617. return;
  71618. }
  71619. var tags = tagsString.split(" ");
  71620. for (var t in tags) {
  71621. Tags._RemoveTagFrom(obj, tags[t]);
  71622. }
  71623. };
  71624. Tags._RemoveTagFrom = function (obj, tag) {
  71625. delete obj._tags[tag];
  71626. };
  71627. Tags.MatchesQuery = function (obj, tagsQuery) {
  71628. if (tagsQuery === undefined) {
  71629. return true;
  71630. }
  71631. if (tagsQuery === "") {
  71632. return Tags.HasTags(obj);
  71633. }
  71634. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71635. };
  71636. return Tags;
  71637. }());
  71638. BABYLON.Tags = Tags;
  71639. })(BABYLON || (BABYLON = {}));
  71640. //# sourceMappingURL=babylon.tags.js.map
  71641. var BABYLON;
  71642. (function (BABYLON) {
  71643. /**
  71644. * Class used to evalaute queries containing `and` and `or` operators
  71645. */
  71646. var AndOrNotEvaluator = /** @class */ (function () {
  71647. function AndOrNotEvaluator() {
  71648. }
  71649. /**
  71650. * Evaluate a query
  71651. * @param query defines the query to evaluate
  71652. * @param evaluateCallback defines the callback used to filter result
  71653. * @returns true if the query matches
  71654. */
  71655. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71656. if (!query.match(/\([^\(\)]*\)/g)) {
  71657. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71658. }
  71659. else {
  71660. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71661. // remove parenthesis
  71662. r = r.slice(1, r.length - 1);
  71663. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71664. });
  71665. }
  71666. if (query === "true") {
  71667. return true;
  71668. }
  71669. if (query === "false") {
  71670. return false;
  71671. }
  71672. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71673. };
  71674. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71675. evaluateCallback = evaluateCallback || (function (r) {
  71676. return r === "true" ? true : false;
  71677. });
  71678. var result;
  71679. var or = parenthesisContent.split("||");
  71680. for (var i in or) {
  71681. if (or.hasOwnProperty(i)) {
  71682. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71683. var and = ori.split("&&");
  71684. if (and.length > 1) {
  71685. for (var j = 0; j < and.length; ++j) {
  71686. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71687. if (andj !== "true" && andj !== "false") {
  71688. if (andj[0] === "!") {
  71689. result = !evaluateCallback(andj.substring(1));
  71690. }
  71691. else {
  71692. result = evaluateCallback(andj);
  71693. }
  71694. }
  71695. else {
  71696. result = andj === "true" ? true : false;
  71697. }
  71698. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71699. ori = "false";
  71700. break;
  71701. }
  71702. }
  71703. }
  71704. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71705. result = true;
  71706. break;
  71707. }
  71708. // result equals false (or undefined)
  71709. if (ori !== "true" && ori !== "false") {
  71710. if (ori[0] === "!") {
  71711. result = !evaluateCallback(ori.substring(1));
  71712. }
  71713. else {
  71714. result = evaluateCallback(ori);
  71715. }
  71716. }
  71717. else {
  71718. result = ori === "true" ? true : false;
  71719. }
  71720. }
  71721. }
  71722. // the whole parenthesis scope is replaced by 'true' or 'false'
  71723. return result ? "true" : "false";
  71724. };
  71725. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  71726. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  71727. // remove whitespaces
  71728. r = r.replace(/[\s]/g, function () { return ""; });
  71729. return r.length % 2 ? "!" : "";
  71730. });
  71731. booleanString = booleanString.trim();
  71732. if (booleanString === "!true") {
  71733. booleanString = "false";
  71734. }
  71735. else if (booleanString === "!false") {
  71736. booleanString = "true";
  71737. }
  71738. return booleanString;
  71739. };
  71740. return AndOrNotEvaluator;
  71741. }());
  71742. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  71743. })(BABYLON || (BABYLON = {}));
  71744. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  71745. var BABYLON;
  71746. (function (BABYLON) {
  71747. /**
  71748. * Class used to enable access to IndexedDB
  71749. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  71750. */
  71751. var Database = /** @class */ (function () {
  71752. /**
  71753. * Creates a new Database
  71754. * @param urlToScene defines the url to load the scene
  71755. * @param callbackManifestChecked defines the callback to use when manifest is checked
  71756. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  71757. */
  71758. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71759. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71760. var _this = this;
  71761. // Handling various flavors of prefixed version of IndexedDB
  71762. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71763. this.callbackManifestChecked = callbackManifestChecked;
  71764. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71765. this.db = null;
  71766. this._enableSceneOffline = false;
  71767. this._enableTexturesOffline = false;
  71768. this.manifestVersionFound = 0;
  71769. this.mustUpdateRessources = false;
  71770. this.hasReachedQuota = false;
  71771. if (!Database.IDBStorageEnabled) {
  71772. this.callbackManifestChecked(true);
  71773. }
  71774. else {
  71775. if (disableManifestCheck) {
  71776. this._enableSceneOffline = true;
  71777. this._enableTexturesOffline = true;
  71778. this.manifestVersionFound = 1;
  71779. BABYLON.Tools.SetImmediate(function () {
  71780. _this.callbackManifestChecked(true);
  71781. });
  71782. }
  71783. else {
  71784. this._checkManifestFile();
  71785. }
  71786. }
  71787. }
  71788. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  71789. /**
  71790. * Gets a boolean indicating if scene must be saved in the database
  71791. */
  71792. get: function () {
  71793. return this._enableSceneOffline;
  71794. },
  71795. enumerable: true,
  71796. configurable: true
  71797. });
  71798. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  71799. /**
  71800. * Gets a boolean indicating if textures must be saved in the database
  71801. */
  71802. get: function () {
  71803. return this._enableTexturesOffline;
  71804. },
  71805. enumerable: true,
  71806. configurable: true
  71807. });
  71808. Database.prototype._checkManifestFile = function () {
  71809. var _this = this;
  71810. var noManifestFile = function () {
  71811. _this._enableSceneOffline = false;
  71812. _this._enableTexturesOffline = false;
  71813. _this.callbackManifestChecked(false);
  71814. };
  71815. var timeStampUsed = false;
  71816. var manifestURL = this.currentSceneUrl + ".manifest";
  71817. var xhr = new XMLHttpRequest();
  71818. if (navigator.onLine) {
  71819. // Adding a timestamp to by-pass browsers' cache
  71820. timeStampUsed = true;
  71821. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  71822. }
  71823. xhr.open("GET", manifestURL, true);
  71824. xhr.addEventListener("load", function () {
  71825. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71826. try {
  71827. var manifestFile = JSON.parse(xhr.response);
  71828. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  71829. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  71830. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  71831. _this.manifestVersionFound = manifestFile.version;
  71832. }
  71833. if (_this.callbackManifestChecked) {
  71834. _this.callbackManifestChecked(true);
  71835. }
  71836. }
  71837. catch (ex) {
  71838. noManifestFile();
  71839. }
  71840. }
  71841. else {
  71842. noManifestFile();
  71843. }
  71844. }, false);
  71845. xhr.addEventListener("error", function (event) {
  71846. if (timeStampUsed) {
  71847. timeStampUsed = false;
  71848. // Let's retry without the timeStamp
  71849. // It could fail when coupled with HTML5 Offline API
  71850. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  71851. xhr.open("GET", retryManifestURL, true);
  71852. xhr.send();
  71853. }
  71854. else {
  71855. noManifestFile();
  71856. }
  71857. }, false);
  71858. try {
  71859. xhr.send();
  71860. }
  71861. catch (ex) {
  71862. BABYLON.Tools.Error("Error on XHR send request.");
  71863. this.callbackManifestChecked(false);
  71864. }
  71865. };
  71866. /**
  71867. * Open the database and make it available
  71868. * @param successCallback defines the callback to call on success
  71869. * @param errorCallback defines the callback to call on error
  71870. */
  71871. Database.prototype.openAsync = function (successCallback, errorCallback) {
  71872. var _this = this;
  71873. var handleError = function () {
  71874. _this.isSupported = false;
  71875. if (errorCallback)
  71876. errorCallback();
  71877. };
  71878. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  71879. // Your browser doesn't support IndexedDB
  71880. this.isSupported = false;
  71881. if (errorCallback)
  71882. errorCallback();
  71883. }
  71884. else {
  71885. // If the DB hasn't been opened or created yet
  71886. if (!this.db) {
  71887. this.hasReachedQuota = false;
  71888. this.isSupported = true;
  71889. var request = this.idbFactory.open("babylonjs", 1);
  71890. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  71891. request.onerror = function (event) {
  71892. handleError();
  71893. };
  71894. // executes when a version change transaction cannot complete due to other active transactions
  71895. request.onblocked = function (event) {
  71896. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  71897. handleError();
  71898. };
  71899. // DB has been opened successfully
  71900. request.onsuccess = function (event) {
  71901. _this.db = request.result;
  71902. successCallback();
  71903. };
  71904. // Initialization of the DB. Creating Scenes & Textures stores
  71905. request.onupgradeneeded = function (event) {
  71906. _this.db = (event.target).result;
  71907. if (_this.db) {
  71908. try {
  71909. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  71910. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  71911. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  71912. }
  71913. catch (ex) {
  71914. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  71915. handleError();
  71916. }
  71917. }
  71918. };
  71919. }
  71920. // DB has already been created and opened
  71921. else {
  71922. if (successCallback)
  71923. successCallback();
  71924. }
  71925. }
  71926. };
  71927. /**
  71928. * Loads an image from the database
  71929. * @param url defines the url to load from
  71930. * @param image defines the target DOM image
  71931. */
  71932. Database.prototype.loadImageFromDB = function (url, image) {
  71933. var _this = this;
  71934. var completeURL = Database._ReturnFullUrlLocation(url);
  71935. var saveAndLoadImage = function () {
  71936. if (!_this.hasReachedQuota && _this.db !== null) {
  71937. // the texture is not yet in the DB, let's try to save it
  71938. _this._saveImageIntoDBAsync(completeURL, image);
  71939. }
  71940. // If the texture is not in the DB and we've reached the DB quota limit
  71941. // let's load it directly from the web
  71942. else {
  71943. image.src = url;
  71944. }
  71945. };
  71946. if (!this.mustUpdateRessources) {
  71947. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  71948. }
  71949. // First time we're download the images or update requested in the manifest file by a version change
  71950. else {
  71951. saveAndLoadImage();
  71952. }
  71953. };
  71954. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  71955. if (this.isSupported && this.db !== null) {
  71956. var texture;
  71957. var transaction = this.db.transaction(["textures"]);
  71958. transaction.onabort = function (event) {
  71959. image.src = url;
  71960. };
  71961. transaction.oncomplete = function (event) {
  71962. var blobTextureURL;
  71963. if (texture) {
  71964. var URL = window.URL || window.webkitURL;
  71965. blobTextureURL = URL.createObjectURL(texture.data);
  71966. image.onerror = function () {
  71967. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  71968. image.src = url;
  71969. };
  71970. image.src = blobTextureURL;
  71971. }
  71972. else {
  71973. notInDBCallback();
  71974. }
  71975. };
  71976. var getRequest = transaction.objectStore("textures").get(url);
  71977. getRequest.onsuccess = function (event) {
  71978. texture = (event.target).result;
  71979. };
  71980. getRequest.onerror = function (event) {
  71981. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  71982. image.src = url;
  71983. };
  71984. }
  71985. else {
  71986. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71987. image.src = url;
  71988. }
  71989. };
  71990. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  71991. var _this = this;
  71992. if (this.isSupported) {
  71993. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  71994. var generateBlobUrl = function () {
  71995. var blobTextureURL;
  71996. if (blob) {
  71997. var URL = window.URL || window.webkitURL;
  71998. try {
  71999. blobTextureURL = URL.createObjectURL(blob);
  72000. }
  72001. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72002. catch (ex) {
  72003. blobTextureURL = URL.createObjectURL(blob);
  72004. }
  72005. }
  72006. if (blobTextureURL) {
  72007. image.src = blobTextureURL;
  72008. }
  72009. };
  72010. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72011. var xhr = new XMLHttpRequest(), blob;
  72012. xhr.open("GET", url, true);
  72013. xhr.responseType = "blob";
  72014. xhr.addEventListener("load", function () {
  72015. if (xhr.status === 200 && _this.db) {
  72016. // Blob as response (XHR2)
  72017. blob = xhr.response;
  72018. var transaction = _this.db.transaction(["textures"], "readwrite");
  72019. // the transaction could abort because of a QuotaExceededError error
  72020. transaction.onabort = function (event) {
  72021. try {
  72022. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72023. var srcElement = (event.srcElement || event.target);
  72024. var error = srcElement.error;
  72025. if (error && error.name === "QuotaExceededError") {
  72026. _this.hasReachedQuota = true;
  72027. }
  72028. }
  72029. catch (ex) { }
  72030. generateBlobUrl();
  72031. };
  72032. transaction.oncomplete = function (event) {
  72033. generateBlobUrl();
  72034. };
  72035. var newTexture = { textureUrl: url, data: blob };
  72036. try {
  72037. // Put the blob into the dabase
  72038. var addRequest = transaction.objectStore("textures").put(newTexture);
  72039. addRequest.onsuccess = function (event) {
  72040. };
  72041. addRequest.onerror = function (event) {
  72042. generateBlobUrl();
  72043. };
  72044. }
  72045. catch (ex) {
  72046. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72047. if (ex.code === 25) {
  72048. Database.IsUASupportingBlobStorage = false;
  72049. }
  72050. image.src = url;
  72051. }
  72052. }
  72053. else {
  72054. image.src = url;
  72055. }
  72056. }, false);
  72057. xhr.addEventListener("error", function (event) {
  72058. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72059. image.src = url;
  72060. }, false);
  72061. xhr.send();
  72062. }
  72063. else {
  72064. image.src = url;
  72065. }
  72066. }
  72067. else {
  72068. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72069. image.src = url;
  72070. }
  72071. };
  72072. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72073. var _this = this;
  72074. var updateVersion = function () {
  72075. // the version is not yet in the DB or we need to update it
  72076. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72077. };
  72078. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72079. };
  72080. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72081. var _this = this;
  72082. if (this.isSupported && this.db) {
  72083. var version;
  72084. try {
  72085. var transaction = this.db.transaction(["versions"]);
  72086. transaction.oncomplete = function (event) {
  72087. if (version) {
  72088. // If the version in the JSON file is different from the version in DB
  72089. if (_this.manifestVersionFound !== version.data) {
  72090. _this.mustUpdateRessources = true;
  72091. updateInDBCallback();
  72092. }
  72093. else {
  72094. callback(version.data);
  72095. }
  72096. }
  72097. // version was not found in DB
  72098. else {
  72099. _this.mustUpdateRessources = true;
  72100. updateInDBCallback();
  72101. }
  72102. };
  72103. transaction.onabort = function (event) {
  72104. callback(-1);
  72105. };
  72106. var getRequest = transaction.objectStore("versions").get(url);
  72107. getRequest.onsuccess = function (event) {
  72108. version = (event.target).result;
  72109. };
  72110. getRequest.onerror = function (event) {
  72111. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72112. callback(-1);
  72113. };
  72114. }
  72115. catch (ex) {
  72116. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72117. callback(-1);
  72118. }
  72119. }
  72120. else {
  72121. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72122. callback(-1);
  72123. }
  72124. };
  72125. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72126. var _this = this;
  72127. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72128. try {
  72129. // Open a transaction to the database
  72130. var transaction = this.db.transaction(["versions"], "readwrite");
  72131. // the transaction could abort because of a QuotaExceededError error
  72132. transaction.onabort = function (event) {
  72133. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72134. var error = event.srcElement['error'];
  72135. if (error && error.name === "QuotaExceededError") {
  72136. _this.hasReachedQuota = true;
  72137. }
  72138. }
  72139. catch (ex) { }
  72140. callback(-1);
  72141. };
  72142. transaction.oncomplete = function (event) {
  72143. callback(_this.manifestVersionFound);
  72144. };
  72145. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72146. // Put the scene into the database
  72147. var addRequest = transaction.objectStore("versions").put(newVersion);
  72148. addRequest.onsuccess = function (event) {
  72149. };
  72150. addRequest.onerror = function (event) {
  72151. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72152. };
  72153. }
  72154. catch (ex) {
  72155. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72156. callback(-1);
  72157. }
  72158. }
  72159. else {
  72160. callback(-1);
  72161. }
  72162. };
  72163. /**
  72164. * Loads a file from database
  72165. * @param url defines the URL to load from
  72166. * @param sceneLoaded defines a callback to call on success
  72167. * @param progressCallBack defines a callback to call when progress changed
  72168. * @param errorCallback defines a callback to call on error
  72169. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72170. */
  72171. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72172. var _this = this;
  72173. var completeUrl = Database._ReturnFullUrlLocation(url);
  72174. var saveAndLoadFile = function () {
  72175. // the scene is not yet in the DB, let's try to save it
  72176. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72177. };
  72178. this._checkVersionFromDB(completeUrl, function (version) {
  72179. if (version !== -1) {
  72180. if (!_this.mustUpdateRessources) {
  72181. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72182. }
  72183. else {
  72184. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72185. }
  72186. }
  72187. else {
  72188. if (errorCallback) {
  72189. errorCallback();
  72190. }
  72191. }
  72192. });
  72193. };
  72194. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72195. if (this.isSupported && this.db) {
  72196. var targetStore;
  72197. if (url.indexOf(".babylon") !== -1) {
  72198. targetStore = "scenes";
  72199. }
  72200. else {
  72201. targetStore = "textures";
  72202. }
  72203. var file;
  72204. var transaction = this.db.transaction([targetStore]);
  72205. transaction.oncomplete = function (event) {
  72206. if (file) {
  72207. callback(file.data);
  72208. }
  72209. // file was not found in DB
  72210. else {
  72211. notInDBCallback();
  72212. }
  72213. };
  72214. transaction.onabort = function (event) {
  72215. notInDBCallback();
  72216. };
  72217. var getRequest = transaction.objectStore(targetStore).get(url);
  72218. getRequest.onsuccess = function (event) {
  72219. file = (event.target).result;
  72220. };
  72221. getRequest.onerror = function (event) {
  72222. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72223. notInDBCallback();
  72224. };
  72225. }
  72226. else {
  72227. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72228. callback();
  72229. }
  72230. };
  72231. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72232. var _this = this;
  72233. if (this.isSupported) {
  72234. var targetStore;
  72235. if (url.indexOf(".babylon") !== -1) {
  72236. targetStore = "scenes";
  72237. }
  72238. else {
  72239. targetStore = "textures";
  72240. }
  72241. // Create XHR
  72242. var xhr = new XMLHttpRequest();
  72243. var fileData;
  72244. xhr.open("GET", url + "?" + Date.now(), true);
  72245. if (useArrayBuffer) {
  72246. xhr.responseType = "arraybuffer";
  72247. }
  72248. if (progressCallback) {
  72249. xhr.onprogress = progressCallback;
  72250. }
  72251. xhr.addEventListener("load", function () {
  72252. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72253. // Blob as response (XHR2)
  72254. //fileData = xhr.responseText;
  72255. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72256. if (!_this.hasReachedQuota && _this.db) {
  72257. // Open a transaction to the database
  72258. var transaction = _this.db.transaction([targetStore], "readwrite");
  72259. // the transaction could abort because of a QuotaExceededError error
  72260. transaction.onabort = function (event) {
  72261. try {
  72262. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72263. var error = event.srcElement['error'];
  72264. if (error && error.name === "QuotaExceededError") {
  72265. _this.hasReachedQuota = true;
  72266. }
  72267. }
  72268. catch (ex) { }
  72269. callback(fileData);
  72270. };
  72271. transaction.oncomplete = function (event) {
  72272. callback(fileData);
  72273. };
  72274. var newFile;
  72275. if (targetStore === "scenes") {
  72276. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72277. }
  72278. else {
  72279. newFile = { textureUrl: url, data: fileData };
  72280. }
  72281. try {
  72282. // Put the scene into the database
  72283. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72284. addRequest.onsuccess = function (event) {
  72285. };
  72286. addRequest.onerror = function (event) {
  72287. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72288. };
  72289. }
  72290. catch (ex) {
  72291. callback(fileData);
  72292. }
  72293. }
  72294. else {
  72295. callback(fileData);
  72296. }
  72297. }
  72298. else {
  72299. if (xhr.status >= 400 && errorCallback) {
  72300. errorCallback(xhr);
  72301. }
  72302. else {
  72303. callback();
  72304. }
  72305. }
  72306. }, false);
  72307. xhr.addEventListener("error", function (event) {
  72308. BABYLON.Tools.Error("error on XHR request.");
  72309. callback();
  72310. }, false);
  72311. xhr.send();
  72312. }
  72313. else {
  72314. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72315. callback();
  72316. }
  72317. };
  72318. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72319. Database.IsUASupportingBlobStorage = true;
  72320. /** Gets a boolean indicating if Database storate is enabled */
  72321. Database.IDBStorageEnabled = true;
  72322. Database._ParseURL = function (url) {
  72323. var a = document.createElement('a');
  72324. a.href = url;
  72325. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72326. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72327. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72328. return absLocation;
  72329. };
  72330. Database._ReturnFullUrlLocation = function (url) {
  72331. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72332. return (Database._ParseURL(window.location.href) + url);
  72333. }
  72334. else {
  72335. return url;
  72336. }
  72337. };
  72338. return Database;
  72339. }());
  72340. BABYLON.Database = Database;
  72341. })(BABYLON || (BABYLON = {}));
  72342. //# sourceMappingURL=babylon.database.js.map
  72343. var BABYLON;
  72344. (function (BABYLON) {
  72345. var FresnelParameters = /** @class */ (function () {
  72346. function FresnelParameters() {
  72347. this._isEnabled = true;
  72348. this.leftColor = BABYLON.Color3.White();
  72349. this.rightColor = BABYLON.Color3.Black();
  72350. this.bias = 0;
  72351. this.power = 1;
  72352. }
  72353. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72354. get: function () {
  72355. return this._isEnabled;
  72356. },
  72357. set: function (value) {
  72358. if (this._isEnabled === value) {
  72359. return;
  72360. }
  72361. this._isEnabled = value;
  72362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72363. },
  72364. enumerable: true,
  72365. configurable: true
  72366. });
  72367. FresnelParameters.prototype.clone = function () {
  72368. var newFresnelParameters = new FresnelParameters();
  72369. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72370. return newFresnelParameters;
  72371. };
  72372. FresnelParameters.prototype.serialize = function () {
  72373. var serializationObject = {};
  72374. serializationObject.isEnabled = this.isEnabled;
  72375. serializationObject.leftColor = this.leftColor.asArray();
  72376. serializationObject.rightColor = this.rightColor.asArray();
  72377. serializationObject.bias = this.bias;
  72378. serializationObject.power = this.power;
  72379. return serializationObject;
  72380. };
  72381. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72382. var fresnelParameters = new FresnelParameters();
  72383. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72384. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72385. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72386. fresnelParameters.bias = parsedFresnelParameters.bias;
  72387. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72388. return fresnelParameters;
  72389. };
  72390. return FresnelParameters;
  72391. }());
  72392. BABYLON.FresnelParameters = FresnelParameters;
  72393. })(BABYLON || (BABYLON = {}));
  72394. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72395. var BABYLON;
  72396. (function (BABYLON) {
  72397. var MultiMaterial = /** @class */ (function (_super) {
  72398. __extends(MultiMaterial, _super);
  72399. function MultiMaterial(name, scene) {
  72400. var _this = _super.call(this, name, scene, true) || this;
  72401. scene.multiMaterials.push(_this);
  72402. _this.subMaterials = new Array();
  72403. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72404. return _this;
  72405. }
  72406. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72407. get: function () {
  72408. return this._subMaterials;
  72409. },
  72410. set: function (value) {
  72411. this._subMaterials = value;
  72412. this._hookArray(value);
  72413. },
  72414. enumerable: true,
  72415. configurable: true
  72416. });
  72417. MultiMaterial.prototype._hookArray = function (array) {
  72418. var _this = this;
  72419. var oldPush = array.push;
  72420. array.push = function () {
  72421. var items = [];
  72422. for (var _i = 0; _i < arguments.length; _i++) {
  72423. items[_i] = arguments[_i];
  72424. }
  72425. var result = oldPush.apply(array, items);
  72426. _this._markAllSubMeshesAsTexturesDirty();
  72427. return result;
  72428. };
  72429. var oldSplice = array.splice;
  72430. array.splice = function (index, deleteCount) {
  72431. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72432. _this._markAllSubMeshesAsTexturesDirty();
  72433. return deleted;
  72434. };
  72435. };
  72436. // Properties
  72437. MultiMaterial.prototype.getSubMaterial = function (index) {
  72438. if (index < 0 || index >= this.subMaterials.length) {
  72439. return this.getScene().defaultMaterial;
  72440. }
  72441. return this.subMaterials[index];
  72442. };
  72443. MultiMaterial.prototype.getActiveTextures = function () {
  72444. var _a;
  72445. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72446. if (subMaterial) {
  72447. return subMaterial.getActiveTextures();
  72448. }
  72449. else {
  72450. return [];
  72451. }
  72452. }));
  72453. };
  72454. // Methods
  72455. MultiMaterial.prototype.getClassName = function () {
  72456. return "MultiMaterial";
  72457. };
  72458. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72459. for (var index = 0; index < this.subMaterials.length; index++) {
  72460. var subMaterial = this.subMaterials[index];
  72461. if (subMaterial) {
  72462. if (subMaterial.storeEffectOnSubMeshes) {
  72463. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72464. return false;
  72465. }
  72466. continue;
  72467. }
  72468. if (!subMaterial.isReady(mesh)) {
  72469. return false;
  72470. }
  72471. }
  72472. }
  72473. return true;
  72474. };
  72475. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72476. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72477. for (var index = 0; index < this.subMaterials.length; index++) {
  72478. var subMaterial = null;
  72479. var current = this.subMaterials[index];
  72480. if (cloneChildren && current) {
  72481. subMaterial = current.clone(name + "-" + current.name);
  72482. }
  72483. else {
  72484. subMaterial = this.subMaterials[index];
  72485. }
  72486. newMultiMaterial.subMaterials.push(subMaterial);
  72487. }
  72488. return newMultiMaterial;
  72489. };
  72490. MultiMaterial.prototype.serialize = function () {
  72491. var serializationObject = {};
  72492. serializationObject.name = this.name;
  72493. serializationObject.id = this.id;
  72494. if (BABYLON.Tags) {
  72495. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72496. }
  72497. serializationObject.materials = [];
  72498. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72499. var subMat = this.subMaterials[matIndex];
  72500. if (subMat) {
  72501. serializationObject.materials.push(subMat.id);
  72502. }
  72503. else {
  72504. serializationObject.materials.push(null);
  72505. }
  72506. }
  72507. return serializationObject;
  72508. };
  72509. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72510. var scene = this.getScene();
  72511. if (!scene) {
  72512. return;
  72513. }
  72514. var index = scene.multiMaterials.indexOf(this);
  72515. if (index >= 0) {
  72516. scene.multiMaterials.splice(index, 1);
  72517. }
  72518. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72519. };
  72520. return MultiMaterial;
  72521. }(BABYLON.Material));
  72522. BABYLON.MultiMaterial = MultiMaterial;
  72523. })(BABYLON || (BABYLON = {}));
  72524. //# sourceMappingURL=babylon.multiMaterial.js.map
  72525. var BABYLON;
  72526. (function (BABYLON) {
  72527. var FreeCameraTouchInput = /** @class */ (function () {
  72528. function FreeCameraTouchInput() {
  72529. this._offsetX = null;
  72530. this._offsetY = null;
  72531. this._pointerPressed = new Array();
  72532. this.touchAngularSensibility = 200000.0;
  72533. this.touchMoveSensibility = 250.0;
  72534. }
  72535. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72536. var _this = this;
  72537. var previousPosition = null;
  72538. if (this._pointerInput === undefined) {
  72539. this._onLostFocus = function (evt) {
  72540. _this._offsetX = null;
  72541. _this._offsetY = null;
  72542. };
  72543. this._pointerInput = function (p, s) {
  72544. var evt = p.event;
  72545. if (evt.pointerType === "mouse") {
  72546. return;
  72547. }
  72548. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72549. if (!noPreventDefault) {
  72550. evt.preventDefault();
  72551. }
  72552. _this._pointerPressed.push(evt.pointerId);
  72553. if (_this._pointerPressed.length !== 1) {
  72554. return;
  72555. }
  72556. previousPosition = {
  72557. x: evt.clientX,
  72558. y: evt.clientY
  72559. };
  72560. }
  72561. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72562. if (!noPreventDefault) {
  72563. evt.preventDefault();
  72564. }
  72565. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72566. if (index === -1) {
  72567. return;
  72568. }
  72569. _this._pointerPressed.splice(index, 1);
  72570. if (index != 0) {
  72571. return;
  72572. }
  72573. previousPosition = null;
  72574. _this._offsetX = null;
  72575. _this._offsetY = null;
  72576. }
  72577. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72578. if (!noPreventDefault) {
  72579. evt.preventDefault();
  72580. }
  72581. if (!previousPosition) {
  72582. return;
  72583. }
  72584. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72585. if (index != 0) {
  72586. return;
  72587. }
  72588. _this._offsetX = evt.clientX - previousPosition.x;
  72589. _this._offsetY = -(evt.clientY - previousPosition.y);
  72590. }
  72591. };
  72592. }
  72593. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72594. if (this._onLostFocus) {
  72595. element.addEventListener("blur", this._onLostFocus);
  72596. }
  72597. };
  72598. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72599. if (this._pointerInput && element) {
  72600. if (this._observer) {
  72601. this.camera.getScene().onPointerObservable.remove(this._observer);
  72602. this._observer = null;
  72603. }
  72604. if (this._onLostFocus) {
  72605. element.removeEventListener("blur", this._onLostFocus);
  72606. this._onLostFocus = null;
  72607. }
  72608. this._pointerPressed = [];
  72609. this._offsetX = null;
  72610. this._offsetY = null;
  72611. }
  72612. };
  72613. FreeCameraTouchInput.prototype.checkInputs = function () {
  72614. if (this._offsetX && this._offsetY) {
  72615. var camera = this.camera;
  72616. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72617. if (this._pointerPressed.length > 1) {
  72618. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72619. }
  72620. else {
  72621. var speed = camera._computeLocalCameraSpeed();
  72622. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72623. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72624. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72625. }
  72626. }
  72627. };
  72628. FreeCameraTouchInput.prototype.getClassName = function () {
  72629. return "FreeCameraTouchInput";
  72630. };
  72631. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72632. return "touch";
  72633. };
  72634. __decorate([
  72635. BABYLON.serialize()
  72636. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72637. __decorate([
  72638. BABYLON.serialize()
  72639. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72640. return FreeCameraTouchInput;
  72641. }());
  72642. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72643. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72644. })(BABYLON || (BABYLON = {}));
  72645. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72646. var BABYLON;
  72647. (function (BABYLON) {
  72648. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72649. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72650. });
  72651. // We're mainly based on the logic defined into the FreeCamera code
  72652. var TouchCamera = /** @class */ (function (_super) {
  72653. __extends(TouchCamera, _super);
  72654. //-- end properties for backward compatibility for inputs
  72655. function TouchCamera(name, position, scene) {
  72656. var _this = _super.call(this, name, position, scene) || this;
  72657. _this.inputs.addTouch();
  72658. _this._setupInputs();
  72659. return _this;
  72660. }
  72661. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72662. //-- Begin properties for backward compatibility for inputs
  72663. get: function () {
  72664. var touch = this.inputs.attached["touch"];
  72665. if (touch)
  72666. return touch.touchAngularSensibility;
  72667. return 0;
  72668. },
  72669. set: function (value) {
  72670. var touch = this.inputs.attached["touch"];
  72671. if (touch)
  72672. touch.touchAngularSensibility = value;
  72673. },
  72674. enumerable: true,
  72675. configurable: true
  72676. });
  72677. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72678. get: function () {
  72679. var touch = this.inputs.attached["touch"];
  72680. if (touch)
  72681. return touch.touchMoveSensibility;
  72682. return 0;
  72683. },
  72684. set: function (value) {
  72685. var touch = this.inputs.attached["touch"];
  72686. if (touch)
  72687. touch.touchMoveSensibility = value;
  72688. },
  72689. enumerable: true,
  72690. configurable: true
  72691. });
  72692. TouchCamera.prototype.getClassName = function () {
  72693. return "TouchCamera";
  72694. };
  72695. /** @hidden */
  72696. TouchCamera.prototype._setupInputs = function () {
  72697. var mouse = this.inputs.attached["mouse"];
  72698. if (mouse) {
  72699. mouse.touchEnabled = false;
  72700. }
  72701. };
  72702. return TouchCamera;
  72703. }(BABYLON.FreeCamera));
  72704. BABYLON.TouchCamera = TouchCamera;
  72705. })(BABYLON || (BABYLON = {}));
  72706. //# sourceMappingURL=babylon.touchCamera.js.map
  72707. var BABYLON;
  72708. (function (BABYLON) {
  72709. var ProceduralTexture = /** @class */ (function (_super) {
  72710. __extends(ProceduralTexture, _super);
  72711. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  72712. if (fallbackTexture === void 0) { fallbackTexture = null; }
  72713. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72714. if (isCube === void 0) { isCube = false; }
  72715. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72716. _this.isCube = isCube;
  72717. _this.isEnabled = true;
  72718. _this._currentRefreshId = -1;
  72719. _this._refreshRate = 1;
  72720. _this._vertexBuffers = {};
  72721. _this._uniforms = new Array();
  72722. _this._samplers = new Array();
  72723. /** @hidden */
  72724. _this._textures = {};
  72725. _this._floats = {};
  72726. _this._ints = {};
  72727. _this._floatsArrays = {};
  72728. _this._colors3 = {};
  72729. _this._colors4 = {};
  72730. _this._vectors2 = {};
  72731. _this._vectors3 = {};
  72732. _this._matrices = {};
  72733. _this._fallbackTextureUsed = false;
  72734. scene = _this.getScene();
  72735. scene.proceduralTextures.push(_this);
  72736. _this._engine = scene.getEngine();
  72737. _this.name = name;
  72738. _this.isRenderTarget = true;
  72739. _this._size = size;
  72740. _this._generateMipMaps = generateMipMaps;
  72741. _this.setFragment(fragment);
  72742. _this._fallbackTexture = fallbackTexture;
  72743. if (isCube) {
  72744. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  72745. _this.setFloat("face", 0);
  72746. }
  72747. else {
  72748. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  72749. }
  72750. // VBO
  72751. var vertices = [];
  72752. vertices.push(1, 1);
  72753. vertices.push(-1, 1);
  72754. vertices.push(-1, -1);
  72755. vertices.push(1, -1);
  72756. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72757. _this._createIndexBuffer();
  72758. return _this;
  72759. }
  72760. ProceduralTexture.prototype._createIndexBuffer = function () {
  72761. var engine = this._engine;
  72762. // Indices
  72763. var indices = [];
  72764. indices.push(0);
  72765. indices.push(1);
  72766. indices.push(2);
  72767. indices.push(0);
  72768. indices.push(2);
  72769. indices.push(3);
  72770. this._indexBuffer = engine.createIndexBuffer(indices);
  72771. };
  72772. /** @hidden */
  72773. ProceduralTexture.prototype._rebuild = function () {
  72774. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72775. if (vb) {
  72776. vb._rebuild();
  72777. }
  72778. this._createIndexBuffer();
  72779. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72780. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72781. }
  72782. };
  72783. ProceduralTexture.prototype.reset = function () {
  72784. if (this._effect === undefined) {
  72785. return;
  72786. }
  72787. var engine = this._engine;
  72788. engine._releaseEffect(this._effect);
  72789. };
  72790. ProceduralTexture.prototype.isReady = function () {
  72791. var _this = this;
  72792. var engine = this._engine;
  72793. var shaders;
  72794. if (!this._fragment) {
  72795. return false;
  72796. }
  72797. if (this._fallbackTextureUsed) {
  72798. return true;
  72799. }
  72800. if (this._fragment.fragmentElement !== undefined) {
  72801. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  72802. }
  72803. else {
  72804. shaders = { vertex: "procedural", fragment: this._fragment };
  72805. }
  72806. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  72807. _this.releaseInternalTexture();
  72808. if (_this._fallbackTexture) {
  72809. _this._texture = _this._fallbackTexture._texture;
  72810. if (_this._texture) {
  72811. _this._texture.incrementReferences();
  72812. }
  72813. }
  72814. _this._fallbackTextureUsed = true;
  72815. });
  72816. return this._effect.isReady();
  72817. };
  72818. ProceduralTexture.prototype.resetRefreshCounter = function () {
  72819. this._currentRefreshId = -1;
  72820. };
  72821. ProceduralTexture.prototype.setFragment = function (fragment) {
  72822. this._fragment = fragment;
  72823. };
  72824. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  72825. get: function () {
  72826. return this._refreshRate;
  72827. },
  72828. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72829. set: function (value) {
  72830. this._refreshRate = value;
  72831. this.resetRefreshCounter();
  72832. },
  72833. enumerable: true,
  72834. configurable: true
  72835. });
  72836. /** @hidden */
  72837. ProceduralTexture.prototype._shouldRender = function () {
  72838. if (!this.isEnabled || !this.isReady() || !this._texture) {
  72839. return false;
  72840. }
  72841. if (this._fallbackTextureUsed) {
  72842. return false;
  72843. }
  72844. if (this._currentRefreshId === -1) { // At least render once
  72845. this._currentRefreshId = 1;
  72846. return true;
  72847. }
  72848. if (this.refreshRate === this._currentRefreshId) {
  72849. this._currentRefreshId = 1;
  72850. return true;
  72851. }
  72852. this._currentRefreshId++;
  72853. return false;
  72854. };
  72855. ProceduralTexture.prototype.getRenderSize = function () {
  72856. return this._size;
  72857. };
  72858. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  72859. if (this._fallbackTextureUsed) {
  72860. return;
  72861. }
  72862. this.releaseInternalTexture();
  72863. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  72864. // Update properties
  72865. this._size = size;
  72866. this._generateMipMaps = generateMipMaps;
  72867. };
  72868. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  72869. if (this._uniforms.indexOf(uniformName) === -1) {
  72870. this._uniforms.push(uniformName);
  72871. }
  72872. };
  72873. ProceduralTexture.prototype.setTexture = function (name, texture) {
  72874. if (this._samplers.indexOf(name) === -1) {
  72875. this._samplers.push(name);
  72876. }
  72877. this._textures[name] = texture;
  72878. return this;
  72879. };
  72880. ProceduralTexture.prototype.setFloat = function (name, value) {
  72881. this._checkUniform(name);
  72882. this._floats[name] = value;
  72883. return this;
  72884. };
  72885. /**
  72886. * Set the value of an uniform to an integer value
  72887. * @param name defines the name of the uniform
  72888. * @param value defines the value to set
  72889. * @returns the current procedural texture
  72890. */
  72891. ProceduralTexture.prototype.setInt = function (name, value) {
  72892. this._checkUniform(name);
  72893. this._ints[name] = value;
  72894. return this;
  72895. };
  72896. ProceduralTexture.prototype.setFloats = function (name, value) {
  72897. this._checkUniform(name);
  72898. this._floatsArrays[name] = value;
  72899. return this;
  72900. };
  72901. ProceduralTexture.prototype.setColor3 = function (name, value) {
  72902. this._checkUniform(name);
  72903. this._colors3[name] = value;
  72904. return this;
  72905. };
  72906. ProceduralTexture.prototype.setColor4 = function (name, value) {
  72907. this._checkUniform(name);
  72908. this._colors4[name] = value;
  72909. return this;
  72910. };
  72911. ProceduralTexture.prototype.setVector2 = function (name, value) {
  72912. this._checkUniform(name);
  72913. this._vectors2[name] = value;
  72914. return this;
  72915. };
  72916. ProceduralTexture.prototype.setVector3 = function (name, value) {
  72917. this._checkUniform(name);
  72918. this._vectors3[name] = value;
  72919. return this;
  72920. };
  72921. ProceduralTexture.prototype.setMatrix = function (name, value) {
  72922. this._checkUniform(name);
  72923. this._matrices[name] = value;
  72924. return this;
  72925. };
  72926. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72927. var scene = this.getScene();
  72928. if (!scene) {
  72929. return;
  72930. }
  72931. var engine = this._engine;
  72932. // Render
  72933. engine.enableEffect(this._effect);
  72934. engine.setState(false);
  72935. // Texture
  72936. for (var name in this._textures) {
  72937. this._effect.setTexture(name, this._textures[name]);
  72938. }
  72939. // Float
  72940. for (name in this._ints) {
  72941. this._effect.setInt(name, this._ints[name]);
  72942. }
  72943. // Float
  72944. for (name in this._floats) {
  72945. this._effect.setFloat(name, this._floats[name]);
  72946. }
  72947. // Floats
  72948. for (name in this._floatsArrays) {
  72949. this._effect.setArray(name, this._floatsArrays[name]);
  72950. }
  72951. // Color3
  72952. for (name in this._colors3) {
  72953. this._effect.setColor3(name, this._colors3[name]);
  72954. }
  72955. // Color4
  72956. for (name in this._colors4) {
  72957. var color = this._colors4[name];
  72958. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  72959. }
  72960. // Vector2
  72961. for (name in this._vectors2) {
  72962. this._effect.setVector2(name, this._vectors2[name]);
  72963. }
  72964. // Vector3
  72965. for (name in this._vectors3) {
  72966. this._effect.setVector3(name, this._vectors3[name]);
  72967. }
  72968. // Matrix
  72969. for (name in this._matrices) {
  72970. this._effect.setMatrix(name, this._matrices[name]);
  72971. }
  72972. if (!this._texture) {
  72973. return;
  72974. }
  72975. if (this.isCube) {
  72976. for (var face = 0; face < 6; face++) {
  72977. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  72978. // VBOs
  72979. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72980. this._effect.setFloat("face", face);
  72981. // Clear
  72982. engine.clear(scene.clearColor, true, true, true);
  72983. // Draw order
  72984. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72985. // Mipmaps
  72986. if (face === 5) {
  72987. engine.generateMipMapsForCubemap(this._texture);
  72988. }
  72989. }
  72990. }
  72991. else {
  72992. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  72993. // VBOs
  72994. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72995. // Clear
  72996. engine.clear(scene.clearColor, true, true, true);
  72997. // Draw order
  72998. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72999. }
  73000. // Unbind
  73001. engine.unBindFramebuffer(this._texture, this.isCube);
  73002. if (this.onGenerated) {
  73003. this.onGenerated();
  73004. }
  73005. };
  73006. ProceduralTexture.prototype.clone = function () {
  73007. var textureSize = this.getSize();
  73008. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73009. // Base texture
  73010. newTexture.hasAlpha = this.hasAlpha;
  73011. newTexture.level = this.level;
  73012. // RenderTarget Texture
  73013. newTexture.coordinatesMode = this.coordinatesMode;
  73014. return newTexture;
  73015. };
  73016. ProceduralTexture.prototype.dispose = function () {
  73017. var scene = this.getScene();
  73018. if (!scene) {
  73019. return;
  73020. }
  73021. var index = scene.proceduralTextures.indexOf(this);
  73022. if (index >= 0) {
  73023. scene.proceduralTextures.splice(index, 1);
  73024. }
  73025. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73026. if (vertexBuffer) {
  73027. vertexBuffer.dispose();
  73028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73029. }
  73030. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73031. this._indexBuffer = null;
  73032. }
  73033. _super.prototype.dispose.call(this);
  73034. };
  73035. __decorate([
  73036. BABYLON.serialize()
  73037. ], ProceduralTexture.prototype, "_size", void 0);
  73038. __decorate([
  73039. BABYLON.serialize()
  73040. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73041. __decorate([
  73042. BABYLON.serialize()
  73043. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73044. __decorate([
  73045. BABYLON.serialize()
  73046. ], ProceduralTexture.prototype, "refreshRate", null);
  73047. return ProceduralTexture;
  73048. }(BABYLON.Texture));
  73049. BABYLON.ProceduralTexture = ProceduralTexture;
  73050. })(BABYLON || (BABYLON = {}));
  73051. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73052. var BABYLON;
  73053. (function (BABYLON) {
  73054. var CustomProceduralTexture = /** @class */ (function (_super) {
  73055. __extends(CustomProceduralTexture, _super);
  73056. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73057. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73058. _this._animate = true;
  73059. _this._time = 0;
  73060. _this._texturePath = texturePath;
  73061. //Try to load json
  73062. _this.loadJson(texturePath);
  73063. _this.refreshRate = 1;
  73064. return _this;
  73065. }
  73066. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73067. var _this = this;
  73068. var noConfigFile = function () {
  73069. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73070. try {
  73071. _this.setFragment(_this._texturePath);
  73072. }
  73073. catch (ex) {
  73074. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73075. }
  73076. };
  73077. var configFileUrl = jsonUrl + "/config.json";
  73078. var xhr = new XMLHttpRequest();
  73079. xhr.open("GET", configFileUrl, true);
  73080. xhr.addEventListener("load", function () {
  73081. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73082. try {
  73083. _this._config = JSON.parse(xhr.response);
  73084. _this.updateShaderUniforms();
  73085. _this.updateTextures();
  73086. _this.setFragment(_this._texturePath + "/custom");
  73087. _this._animate = _this._config.animate;
  73088. _this.refreshRate = _this._config.refreshrate;
  73089. }
  73090. catch (ex) {
  73091. noConfigFile();
  73092. }
  73093. }
  73094. else {
  73095. noConfigFile();
  73096. }
  73097. }, false);
  73098. xhr.addEventListener("error", function () {
  73099. noConfigFile();
  73100. }, false);
  73101. try {
  73102. xhr.send();
  73103. }
  73104. catch (ex) {
  73105. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73106. }
  73107. };
  73108. CustomProceduralTexture.prototype.isReady = function () {
  73109. if (!_super.prototype.isReady.call(this)) {
  73110. return false;
  73111. }
  73112. for (var name in this._textures) {
  73113. var texture = this._textures[name];
  73114. if (!texture.isReady()) {
  73115. return false;
  73116. }
  73117. }
  73118. return true;
  73119. };
  73120. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73121. var scene = this.getScene();
  73122. if (this._animate && scene) {
  73123. this._time += scene.getAnimationRatio() * 0.03;
  73124. this.updateShaderUniforms();
  73125. }
  73126. _super.prototype.render.call(this, useCameraPostProcess);
  73127. };
  73128. CustomProceduralTexture.prototype.updateTextures = function () {
  73129. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73130. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73131. }
  73132. };
  73133. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73134. if (this._config) {
  73135. for (var j = 0; j < this._config.uniforms.length; j++) {
  73136. var uniform = this._config.uniforms[j];
  73137. switch (uniform.type) {
  73138. case "float":
  73139. this.setFloat(uniform.name, uniform.value);
  73140. break;
  73141. case "color3":
  73142. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73143. break;
  73144. case "color4":
  73145. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73146. break;
  73147. case "vector2":
  73148. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73149. break;
  73150. case "vector3":
  73151. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73152. break;
  73153. }
  73154. }
  73155. }
  73156. this.setFloat("time", this._time);
  73157. };
  73158. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73159. get: function () {
  73160. return this._animate;
  73161. },
  73162. set: function (value) {
  73163. this._animate = value;
  73164. },
  73165. enumerable: true,
  73166. configurable: true
  73167. });
  73168. return CustomProceduralTexture;
  73169. }(BABYLON.ProceduralTexture));
  73170. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73171. })(BABYLON || (BABYLON = {}));
  73172. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73173. var BABYLON;
  73174. (function (BABYLON) {
  73175. var FreeCameraGamepadInput = /** @class */ (function () {
  73176. function FreeCameraGamepadInput() {
  73177. this.gamepadAngularSensibility = 200;
  73178. this.gamepadMoveSensibility = 40;
  73179. // private members
  73180. this._cameraTransform = BABYLON.Matrix.Identity();
  73181. this._deltaTransform = BABYLON.Vector3.Zero();
  73182. this._vector3 = BABYLON.Vector3.Zero();
  73183. this._vector2 = BABYLON.Vector2.Zero();
  73184. }
  73185. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73186. var _this = this;
  73187. var manager = this.camera.getScene().gamepadManager;
  73188. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73189. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73190. // prioritize XBOX gamepads.
  73191. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73192. _this.gamepad = gamepad;
  73193. }
  73194. }
  73195. });
  73196. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73197. if (_this.gamepad === gamepad) {
  73198. _this.gamepad = null;
  73199. }
  73200. });
  73201. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73202. };
  73203. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73204. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73205. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73206. this.gamepad = null;
  73207. };
  73208. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73209. if (this.gamepad && this.gamepad.leftStick) {
  73210. var camera = this.camera;
  73211. var LSValues = this.gamepad.leftStick;
  73212. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73213. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73214. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73215. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73216. var RSValues = this.gamepad.rightStick;
  73217. if (RSValues) {
  73218. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73219. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73220. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73221. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73222. }
  73223. else {
  73224. RSValues = { x: 0, y: 0 };
  73225. }
  73226. if (!camera.rotationQuaternion) {
  73227. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73228. }
  73229. else {
  73230. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73231. }
  73232. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73233. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73234. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73235. camera.cameraDirection.addInPlace(this._deltaTransform);
  73236. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73237. camera.cameraRotation.addInPlace(this._vector2);
  73238. }
  73239. };
  73240. FreeCameraGamepadInput.prototype.getClassName = function () {
  73241. return "FreeCameraGamepadInput";
  73242. };
  73243. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73244. return "gamepad";
  73245. };
  73246. __decorate([
  73247. BABYLON.serialize()
  73248. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73249. __decorate([
  73250. BABYLON.serialize()
  73251. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73252. return FreeCameraGamepadInput;
  73253. }());
  73254. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73255. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73256. })(BABYLON || (BABYLON = {}));
  73257. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73258. var BABYLON;
  73259. (function (BABYLON) {
  73260. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73261. function ArcRotateCameraGamepadInput() {
  73262. this.gamepadRotationSensibility = 80;
  73263. this.gamepadMoveSensibility = 40;
  73264. }
  73265. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73266. var _this = this;
  73267. var manager = this.camera.getScene().gamepadManager;
  73268. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73269. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73270. // prioritize XBOX gamepads.
  73271. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73272. _this.gamepad = gamepad;
  73273. }
  73274. }
  73275. });
  73276. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73277. if (_this.gamepad === gamepad) {
  73278. _this.gamepad = null;
  73279. }
  73280. });
  73281. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73282. };
  73283. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73284. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73285. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73286. this.gamepad = null;
  73287. };
  73288. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73289. if (this.gamepad) {
  73290. var camera = this.camera;
  73291. var RSValues = this.gamepad.rightStick;
  73292. if (RSValues) {
  73293. if (RSValues.x != 0) {
  73294. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73295. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73296. camera.inertialAlphaOffset += normalizedRX;
  73297. }
  73298. }
  73299. if (RSValues.y != 0) {
  73300. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73301. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73302. camera.inertialBetaOffset += normalizedRY;
  73303. }
  73304. }
  73305. }
  73306. var LSValues = this.gamepad.leftStick;
  73307. if (LSValues && LSValues.y != 0) {
  73308. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73309. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73310. this.camera.inertialRadiusOffset -= normalizedLY;
  73311. }
  73312. }
  73313. }
  73314. };
  73315. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73316. return "ArcRotateCameraGamepadInput";
  73317. };
  73318. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73319. return "gamepad";
  73320. };
  73321. __decorate([
  73322. BABYLON.serialize()
  73323. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73324. __decorate([
  73325. BABYLON.serialize()
  73326. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73327. return ArcRotateCameraGamepadInput;
  73328. }());
  73329. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73330. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73331. })(BABYLON || (BABYLON = {}));
  73332. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73333. var BABYLON;
  73334. (function (BABYLON) {
  73335. var GamepadManager = /** @class */ (function () {
  73336. function GamepadManager(_scene) {
  73337. var _this = this;
  73338. this._scene = _scene;
  73339. this._babylonGamepads = [];
  73340. this._oneGamepadConnected = false;
  73341. /** @hidden */
  73342. this._isMonitoring = false;
  73343. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73344. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73345. this._gamepadEventSupported = false;
  73346. }
  73347. else {
  73348. this._gamepadEventSupported = 'GamepadEvent' in window;
  73349. this._gamepadSupport = (navigator.getGamepads ||
  73350. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73351. }
  73352. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73353. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73354. for (var i in _this._babylonGamepads) {
  73355. var gamepad = _this._babylonGamepads[i];
  73356. if (gamepad && gamepad._isConnected) {
  73357. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73358. }
  73359. }
  73360. });
  73361. this._onGamepadConnectedEvent = function (evt) {
  73362. var gamepad = evt.gamepad;
  73363. if (gamepad.index in _this._babylonGamepads) {
  73364. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73365. return;
  73366. }
  73367. }
  73368. var newGamepad;
  73369. if (_this._babylonGamepads[gamepad.index]) {
  73370. newGamepad = _this._babylonGamepads[gamepad.index];
  73371. newGamepad.browserGamepad = gamepad;
  73372. newGamepad._isConnected = true;
  73373. }
  73374. else {
  73375. newGamepad = _this._addNewGamepad(gamepad);
  73376. }
  73377. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73378. _this._startMonitoringGamepads();
  73379. };
  73380. this._onGamepadDisconnectedEvent = function (evt) {
  73381. var gamepad = evt.gamepad;
  73382. // Remove the gamepad from the list of gamepads to monitor.
  73383. for (var i in _this._babylonGamepads) {
  73384. if (_this._babylonGamepads[i].index === gamepad.index) {
  73385. var disconnectedGamepad = _this._babylonGamepads[i];
  73386. disconnectedGamepad._isConnected = false;
  73387. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73388. break;
  73389. }
  73390. }
  73391. };
  73392. if (this._gamepadSupport) {
  73393. //first add already-connected gamepads
  73394. this._updateGamepadObjects();
  73395. if (this._babylonGamepads.length) {
  73396. this._startMonitoringGamepads();
  73397. }
  73398. // Checking if the gamepad connected event is supported (like in Firefox)
  73399. if (this._gamepadEventSupported) {
  73400. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73401. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73402. }
  73403. else {
  73404. this._startMonitoringGamepads();
  73405. }
  73406. }
  73407. }
  73408. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73409. get: function () {
  73410. return this._babylonGamepads;
  73411. },
  73412. enumerable: true,
  73413. configurable: true
  73414. });
  73415. GamepadManager.prototype.getGamepadByType = function (type) {
  73416. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73417. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73418. var gamepad = _a[_i];
  73419. if (gamepad && gamepad.type === type) {
  73420. return gamepad;
  73421. }
  73422. }
  73423. return null;
  73424. };
  73425. GamepadManager.prototype.dispose = function () {
  73426. if (this._gamepadEventSupported) {
  73427. if (this._onGamepadConnectedEvent) {
  73428. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73429. }
  73430. if (this._onGamepadDisconnectedEvent) {
  73431. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73432. }
  73433. this._onGamepadConnectedEvent = null;
  73434. this._onGamepadDisconnectedEvent = null;
  73435. }
  73436. this._babylonGamepads.forEach(function (gamepad) {
  73437. gamepad.dispose();
  73438. });
  73439. this.onGamepadConnectedObservable.clear();
  73440. this.onGamepadDisconnectedObservable.clear();
  73441. this._oneGamepadConnected = false;
  73442. this._stopMonitoringGamepads();
  73443. this._babylonGamepads = [];
  73444. };
  73445. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73446. if (!this._oneGamepadConnected) {
  73447. this._oneGamepadConnected = true;
  73448. }
  73449. var newGamepad;
  73450. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73451. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73452. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73453. }
  73454. // if pose is supported, use the (WebVR) pose enabled controller
  73455. else if (gamepad.pose) {
  73456. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73457. }
  73458. else {
  73459. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73460. }
  73461. this._babylonGamepads[newGamepad.index] = newGamepad;
  73462. return newGamepad;
  73463. };
  73464. GamepadManager.prototype._startMonitoringGamepads = function () {
  73465. if (!this._isMonitoring) {
  73466. this._isMonitoring = true;
  73467. //back-comp
  73468. if (!this._scene) {
  73469. this._checkGamepadsStatus();
  73470. }
  73471. }
  73472. };
  73473. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73474. this._isMonitoring = false;
  73475. };
  73476. /** @hidden */
  73477. GamepadManager.prototype._checkGamepadsStatus = function () {
  73478. var _this = this;
  73479. // Hack to be compatible Chrome
  73480. this._updateGamepadObjects();
  73481. for (var i in this._babylonGamepads) {
  73482. var gamepad = this._babylonGamepads[i];
  73483. if (!gamepad || !gamepad.isConnected) {
  73484. continue;
  73485. }
  73486. gamepad.update();
  73487. }
  73488. if (this._isMonitoring && !this._scene) {
  73489. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73490. }
  73491. };
  73492. // This function is called only on Chrome, which does not properly support
  73493. // connection/disconnection events and forces you to recopy again the gamepad object
  73494. GamepadManager.prototype._updateGamepadObjects = function () {
  73495. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73496. for (var i = 0; i < gamepads.length; i++) {
  73497. var gamepad = gamepads[i];
  73498. if (gamepad) {
  73499. if (!this._babylonGamepads[gamepad.index]) {
  73500. var newGamepad = this._addNewGamepad(gamepad);
  73501. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73502. }
  73503. else {
  73504. // Forced to copy again this object for Chrome for unknown reason
  73505. this._babylonGamepads[i].browserGamepad = gamepad;
  73506. if (!this._babylonGamepads[i].isConnected) {
  73507. this._babylonGamepads[i]._isConnected = true;
  73508. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73509. }
  73510. }
  73511. }
  73512. }
  73513. };
  73514. return GamepadManager;
  73515. }());
  73516. BABYLON.GamepadManager = GamepadManager;
  73517. })(BABYLON || (BABYLON = {}));
  73518. //# sourceMappingURL=babylon.gamepadManager.js.map
  73519. var BABYLON;
  73520. (function (BABYLON) {
  73521. var StickValues = /** @class */ (function () {
  73522. function StickValues(x, y) {
  73523. this.x = x;
  73524. this.y = y;
  73525. }
  73526. return StickValues;
  73527. }());
  73528. BABYLON.StickValues = StickValues;
  73529. var Gamepad = /** @class */ (function () {
  73530. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73531. if (leftStickX === void 0) { leftStickX = 0; }
  73532. if (leftStickY === void 0) { leftStickY = 1; }
  73533. if (rightStickX === void 0) { rightStickX = 2; }
  73534. if (rightStickY === void 0) { rightStickY = 3; }
  73535. this.id = id;
  73536. this.index = index;
  73537. this.browserGamepad = browserGamepad;
  73538. this._leftStick = { x: 0, y: 0 };
  73539. this._rightStick = { x: 0, y: 0 };
  73540. /** @hidden */
  73541. this._isConnected = true;
  73542. this._invertLeftStickY = false;
  73543. this.type = Gamepad.GAMEPAD;
  73544. this._leftStickAxisX = leftStickX;
  73545. this._leftStickAxisY = leftStickY;
  73546. this._rightStickAxisX = rightStickX;
  73547. this._rightStickAxisY = rightStickY;
  73548. if (this.browserGamepad.axes.length >= 2) {
  73549. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73550. }
  73551. if (this.browserGamepad.axes.length >= 4) {
  73552. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73553. }
  73554. }
  73555. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73556. get: function () {
  73557. return this._isConnected;
  73558. },
  73559. enumerable: true,
  73560. configurable: true
  73561. });
  73562. Gamepad.prototype.onleftstickchanged = function (callback) {
  73563. this._onleftstickchanged = callback;
  73564. };
  73565. Gamepad.prototype.onrightstickchanged = function (callback) {
  73566. this._onrightstickchanged = callback;
  73567. };
  73568. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73569. get: function () {
  73570. return this._leftStick;
  73571. },
  73572. set: function (newValues) {
  73573. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73574. this._onleftstickchanged(newValues);
  73575. }
  73576. this._leftStick = newValues;
  73577. },
  73578. enumerable: true,
  73579. configurable: true
  73580. });
  73581. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73582. get: function () {
  73583. return this._rightStick;
  73584. },
  73585. set: function (newValues) {
  73586. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73587. this._onrightstickchanged(newValues);
  73588. }
  73589. this._rightStick = newValues;
  73590. },
  73591. enumerable: true,
  73592. configurable: true
  73593. });
  73594. Gamepad.prototype.update = function () {
  73595. if (this._leftStick) {
  73596. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73597. if (this._invertLeftStickY) {
  73598. this.leftStick.y *= -1;
  73599. }
  73600. }
  73601. if (this._rightStick) {
  73602. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73603. }
  73604. };
  73605. Gamepad.prototype.dispose = function () {
  73606. };
  73607. Gamepad.GAMEPAD = 0;
  73608. Gamepad.GENERIC = 1;
  73609. Gamepad.XBOX = 2;
  73610. Gamepad.POSE_ENABLED = 3;
  73611. return Gamepad;
  73612. }());
  73613. BABYLON.Gamepad = Gamepad;
  73614. var GenericPad = /** @class */ (function (_super) {
  73615. __extends(GenericPad, _super);
  73616. function GenericPad(id, index, browserGamepad) {
  73617. var _this = _super.call(this, id, index, browserGamepad) || this;
  73618. _this.onButtonDownObservable = new BABYLON.Observable();
  73619. _this.onButtonUpObservable = new BABYLON.Observable();
  73620. _this.type = Gamepad.GENERIC;
  73621. _this._buttons = new Array(browserGamepad.buttons.length);
  73622. return _this;
  73623. }
  73624. GenericPad.prototype.onbuttondown = function (callback) {
  73625. this._onbuttondown = callback;
  73626. };
  73627. GenericPad.prototype.onbuttonup = function (callback) {
  73628. this._onbuttonup = callback;
  73629. };
  73630. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73631. if (newValue !== currentValue) {
  73632. if (newValue === 1) {
  73633. if (this._onbuttondown) {
  73634. this._onbuttondown(buttonIndex);
  73635. }
  73636. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73637. }
  73638. if (newValue === 0) {
  73639. if (this._onbuttonup) {
  73640. this._onbuttonup(buttonIndex);
  73641. }
  73642. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73643. }
  73644. }
  73645. return newValue;
  73646. };
  73647. GenericPad.prototype.update = function () {
  73648. _super.prototype.update.call(this);
  73649. for (var index = 0; index < this._buttons.length; index++) {
  73650. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73651. }
  73652. };
  73653. GenericPad.prototype.dispose = function () {
  73654. _super.prototype.dispose.call(this);
  73655. this.onButtonDownObservable.clear();
  73656. this.onButtonUpObservable.clear();
  73657. };
  73658. return GenericPad;
  73659. }(Gamepad));
  73660. BABYLON.GenericPad = GenericPad;
  73661. })(BABYLON || (BABYLON = {}));
  73662. //# sourceMappingURL=babylon.gamepad.js.map
  73663. var BABYLON;
  73664. (function (BABYLON) {
  73665. /**
  73666. * Defines supported buttons for XBox360 compatible gamepads
  73667. */
  73668. var Xbox360Button;
  73669. (function (Xbox360Button) {
  73670. /** A */
  73671. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73672. /** B */
  73673. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73674. /** X */
  73675. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73676. /** Y */
  73677. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73678. /** Start */
  73679. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73680. /** Back */
  73681. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73682. /** Left button */
  73683. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73684. /** Right button */
  73685. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73686. /** Left stick */
  73687. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73688. /** Right stick */
  73689. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73690. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73691. /** Defines values for XBox360 DPad */
  73692. var Xbox360Dpad;
  73693. (function (Xbox360Dpad) {
  73694. /** Up */
  73695. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73696. /** Down */
  73697. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73698. /** Left */
  73699. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73700. /** Right */
  73701. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73702. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73703. /**
  73704. * Defines a XBox360 gamepad
  73705. */
  73706. var Xbox360Pad = /** @class */ (function (_super) {
  73707. __extends(Xbox360Pad, _super);
  73708. /**
  73709. * Creates a new XBox360 gamepad object
  73710. * @param id defines the id of this gamepad
  73711. * @param index defines its index
  73712. * @param gamepad defines the internal HTML gamepad object
  73713. * @param xboxOne defines if it is a XBox One gamepad
  73714. */
  73715. function Xbox360Pad(id, index, gamepad, xboxOne) {
  73716. if (xboxOne === void 0) { xboxOne = false; }
  73717. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  73718. _this._leftTrigger = 0;
  73719. _this._rightTrigger = 0;
  73720. /** Observable raised when a button is pressed */
  73721. _this.onButtonDownObservable = new BABYLON.Observable();
  73722. /** Observable raised when a button is released */
  73723. _this.onButtonUpObservable = new BABYLON.Observable();
  73724. /** Observable raised when a pad is pressed */
  73725. _this.onPadDownObservable = new BABYLON.Observable();
  73726. /** Observable raised when a pad is released */
  73727. _this.onPadUpObservable = new BABYLON.Observable();
  73728. _this._buttonA = 0;
  73729. _this._buttonB = 0;
  73730. _this._buttonX = 0;
  73731. _this._buttonY = 0;
  73732. _this._buttonBack = 0;
  73733. _this._buttonStart = 0;
  73734. _this._buttonLB = 0;
  73735. _this._buttonRB = 0;
  73736. _this._buttonLeftStick = 0;
  73737. _this._buttonRightStick = 0;
  73738. _this._dPadUp = 0;
  73739. _this._dPadDown = 0;
  73740. _this._dPadLeft = 0;
  73741. _this._dPadRight = 0;
  73742. _this._isXboxOnePad = false;
  73743. _this.type = BABYLON.Gamepad.XBOX;
  73744. _this._isXboxOnePad = xboxOne;
  73745. return _this;
  73746. }
  73747. /**
  73748. * Defines the callback to call when left trigger is pressed
  73749. * @param callback defines the callback to use
  73750. */
  73751. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  73752. this._onlefttriggerchanged = callback;
  73753. };
  73754. /**
  73755. * Defines the callback to call when right trigger is pressed
  73756. * @param callback defines the callback to use
  73757. */
  73758. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  73759. this._onrighttriggerchanged = callback;
  73760. };
  73761. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  73762. /**
  73763. * Gets or sets left trigger value
  73764. */
  73765. get: function () {
  73766. return this._leftTrigger;
  73767. },
  73768. set: function (newValue) {
  73769. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73770. this._onlefttriggerchanged(newValue);
  73771. }
  73772. this._leftTrigger = newValue;
  73773. },
  73774. enumerable: true,
  73775. configurable: true
  73776. });
  73777. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  73778. /**
  73779. * Gets or sets right trigger value
  73780. */
  73781. get: function () {
  73782. return this._rightTrigger;
  73783. },
  73784. set: function (newValue) {
  73785. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  73786. this._onrighttriggerchanged(newValue);
  73787. }
  73788. this._rightTrigger = newValue;
  73789. },
  73790. enumerable: true,
  73791. configurable: true
  73792. });
  73793. /**
  73794. * Defines the callback to call when a button is pressed
  73795. * @param callback defines the callback to use
  73796. */
  73797. Xbox360Pad.prototype.onbuttondown = function (callback) {
  73798. this._onbuttondown = callback;
  73799. };
  73800. /**
  73801. * Defines the callback to call when a button is released
  73802. * @param callback defines the callback to use
  73803. */
  73804. Xbox360Pad.prototype.onbuttonup = function (callback) {
  73805. this._onbuttonup = callback;
  73806. };
  73807. /**
  73808. * Defines the callback to call when a pad is pressed
  73809. * @param callback defines the callback to use
  73810. */
  73811. Xbox360Pad.prototype.ondpaddown = function (callback) {
  73812. this._ondpaddown = callback;
  73813. };
  73814. /**
  73815. * Defines the callback to call when a pad is released
  73816. * @param callback defines the callback to use
  73817. */
  73818. Xbox360Pad.prototype.ondpadup = function (callback) {
  73819. this._ondpadup = callback;
  73820. };
  73821. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  73822. if (newValue !== currentValue) {
  73823. if (newValue === 1) {
  73824. if (this._onbuttondown) {
  73825. this._onbuttondown(buttonType);
  73826. }
  73827. this.onButtonDownObservable.notifyObservers(buttonType);
  73828. }
  73829. if (newValue === 0) {
  73830. if (this._onbuttonup) {
  73831. this._onbuttonup(buttonType);
  73832. }
  73833. this.onButtonUpObservable.notifyObservers(buttonType);
  73834. }
  73835. }
  73836. return newValue;
  73837. };
  73838. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  73839. if (newValue !== currentValue) {
  73840. if (newValue === 1) {
  73841. if (this._ondpaddown) {
  73842. this._ondpaddown(buttonType);
  73843. }
  73844. this.onPadDownObservable.notifyObservers(buttonType);
  73845. }
  73846. if (newValue === 0) {
  73847. if (this._ondpadup) {
  73848. this._ondpadup(buttonType);
  73849. }
  73850. this.onPadUpObservable.notifyObservers(buttonType);
  73851. }
  73852. }
  73853. return newValue;
  73854. };
  73855. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  73856. /** Gets or sets value of A button */
  73857. get: function () {
  73858. return this._buttonA;
  73859. },
  73860. set: function (value) {
  73861. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  73862. },
  73863. enumerable: true,
  73864. configurable: true
  73865. });
  73866. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  73867. /** Gets or sets value of B button */
  73868. get: function () {
  73869. return this._buttonB;
  73870. },
  73871. set: function (value) {
  73872. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  73873. },
  73874. enumerable: true,
  73875. configurable: true
  73876. });
  73877. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  73878. /** Gets or sets value of X button */
  73879. get: function () {
  73880. return this._buttonX;
  73881. },
  73882. set: function (value) {
  73883. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  73889. /** Gets or sets value of Y button */
  73890. get: function () {
  73891. return this._buttonY;
  73892. },
  73893. set: function (value) {
  73894. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  73895. },
  73896. enumerable: true,
  73897. configurable: true
  73898. });
  73899. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  73900. /** Gets or sets value of Start button */
  73901. get: function () {
  73902. return this._buttonStart;
  73903. },
  73904. set: function (value) {
  73905. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  73906. },
  73907. enumerable: true,
  73908. configurable: true
  73909. });
  73910. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  73911. /** Gets or sets value of Back button */
  73912. get: function () {
  73913. return this._buttonBack;
  73914. },
  73915. set: function (value) {
  73916. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  73917. },
  73918. enumerable: true,
  73919. configurable: true
  73920. });
  73921. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  73922. /** Gets or sets value of Left button */
  73923. get: function () {
  73924. return this._buttonLB;
  73925. },
  73926. set: function (value) {
  73927. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  73928. },
  73929. enumerable: true,
  73930. configurable: true
  73931. });
  73932. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  73933. /** Gets or sets value of Right button */
  73934. get: function () {
  73935. return this._buttonRB;
  73936. },
  73937. set: function (value) {
  73938. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  73939. },
  73940. enumerable: true,
  73941. configurable: true
  73942. });
  73943. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  73944. /** Gets or sets value of left stick */
  73945. get: function () {
  73946. return this._buttonLeftStick;
  73947. },
  73948. set: function (value) {
  73949. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  73950. },
  73951. enumerable: true,
  73952. configurable: true
  73953. });
  73954. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  73955. /** Gets or sets value of right stick */
  73956. get: function () {
  73957. return this._buttonRightStick;
  73958. },
  73959. set: function (value) {
  73960. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  73961. },
  73962. enumerable: true,
  73963. configurable: true
  73964. });
  73965. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  73966. /** Gets or sets value of DPad up */
  73967. get: function () {
  73968. return this._dPadUp;
  73969. },
  73970. set: function (value) {
  73971. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  73972. },
  73973. enumerable: true,
  73974. configurable: true
  73975. });
  73976. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  73977. /** Gets or sets value of DPad down */
  73978. get: function () {
  73979. return this._dPadDown;
  73980. },
  73981. set: function (value) {
  73982. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  73983. },
  73984. enumerable: true,
  73985. configurable: true
  73986. });
  73987. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  73988. /** Gets or sets value of DPad left */
  73989. get: function () {
  73990. return this._dPadLeft;
  73991. },
  73992. set: function (value) {
  73993. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  73994. },
  73995. enumerable: true,
  73996. configurable: true
  73997. });
  73998. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  73999. /** Gets or sets value of DPad right */
  74000. get: function () {
  74001. return this._dPadRight;
  74002. },
  74003. set: function (value) {
  74004. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74005. },
  74006. enumerable: true,
  74007. configurable: true
  74008. });
  74009. /**
  74010. * Force the gamepad to synchronize with device values
  74011. */
  74012. Xbox360Pad.prototype.update = function () {
  74013. _super.prototype.update.call(this);
  74014. if (this._isXboxOnePad) {
  74015. this.buttonA = this.browserGamepad.buttons[0].value;
  74016. this.buttonB = this.browserGamepad.buttons[1].value;
  74017. this.buttonX = this.browserGamepad.buttons[2].value;
  74018. this.buttonY = this.browserGamepad.buttons[3].value;
  74019. this.buttonLB = this.browserGamepad.buttons[4].value;
  74020. this.buttonRB = this.browserGamepad.buttons[5].value;
  74021. this.leftTrigger = this.browserGamepad.axes[2];
  74022. this.rightTrigger = this.browserGamepad.axes[5];
  74023. this.buttonBack = this.browserGamepad.buttons[9].value;
  74024. this.buttonStart = this.browserGamepad.buttons[8].value;
  74025. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74026. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74027. this.dPadUp = this.browserGamepad.buttons[11].value;
  74028. this.dPadDown = this.browserGamepad.buttons[12].value;
  74029. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74030. this.dPadRight = this.browserGamepad.buttons[14].value;
  74031. }
  74032. else {
  74033. this.buttonA = this.browserGamepad.buttons[0].value;
  74034. this.buttonB = this.browserGamepad.buttons[1].value;
  74035. this.buttonX = this.browserGamepad.buttons[2].value;
  74036. this.buttonY = this.browserGamepad.buttons[3].value;
  74037. this.buttonLB = this.browserGamepad.buttons[4].value;
  74038. this.buttonRB = this.browserGamepad.buttons[5].value;
  74039. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74040. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74041. this.buttonBack = this.browserGamepad.buttons[8].value;
  74042. this.buttonStart = this.browserGamepad.buttons[9].value;
  74043. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74044. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74045. this.dPadUp = this.browserGamepad.buttons[12].value;
  74046. this.dPadDown = this.browserGamepad.buttons[13].value;
  74047. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74048. this.dPadRight = this.browserGamepad.buttons[15].value;
  74049. }
  74050. };
  74051. Xbox360Pad.prototype.dispose = function () {
  74052. _super.prototype.dispose.call(this);
  74053. this.onButtonDownObservable.clear();
  74054. this.onButtonUpObservable.clear();
  74055. this.onPadDownObservable.clear();
  74056. this.onPadUpObservable.clear();
  74057. };
  74058. return Xbox360Pad;
  74059. }(BABYLON.Gamepad));
  74060. BABYLON.Xbox360Pad = Xbox360Pad;
  74061. })(BABYLON || (BABYLON = {}));
  74062. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74063. var BABYLON;
  74064. (function (BABYLON) {
  74065. /**
  74066. * Defines the types of pose enabled controllers that are supported
  74067. */
  74068. var PoseEnabledControllerType;
  74069. (function (PoseEnabledControllerType) {
  74070. /**
  74071. * HTC Vive
  74072. */
  74073. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74074. /**
  74075. * Oculus Rift
  74076. */
  74077. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74078. /**
  74079. * Windows mixed reality
  74080. */
  74081. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74082. /**
  74083. * Samsung gear VR
  74084. */
  74085. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74086. /**
  74087. * Google Daydream
  74088. */
  74089. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74090. /**
  74091. * Generic
  74092. */
  74093. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74094. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74095. /**
  74096. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74097. */
  74098. var PoseEnabledControllerHelper = /** @class */ (function () {
  74099. function PoseEnabledControllerHelper() {
  74100. }
  74101. /**
  74102. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74103. * @param vrGamepad the gamepad to initialized
  74104. * @returns a vr controller of the type the gamepad identified as
  74105. */
  74106. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74107. // Oculus Touch
  74108. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74109. return new BABYLON.OculusTouchController(vrGamepad);
  74110. }
  74111. // Windows Mixed Reality controllers
  74112. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74113. return new BABYLON.WindowsMotionController(vrGamepad);
  74114. }
  74115. // HTC Vive
  74116. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74117. return new BABYLON.ViveController(vrGamepad);
  74118. }
  74119. // Samsung/Oculus Gear VR or Oculus Go
  74120. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74121. return new BABYLON.GearVRController(vrGamepad);
  74122. }
  74123. // Google Daydream
  74124. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74125. return new BABYLON.DaydreamController(vrGamepad);
  74126. }
  74127. // Generic
  74128. else {
  74129. return new BABYLON.GenericController(vrGamepad);
  74130. }
  74131. };
  74132. return PoseEnabledControllerHelper;
  74133. }());
  74134. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74135. /**
  74136. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74137. */
  74138. var PoseEnabledController = /** @class */ (function (_super) {
  74139. __extends(PoseEnabledController, _super);
  74140. /**
  74141. * Creates a new PoseEnabledController from a gamepad
  74142. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74143. */
  74144. function PoseEnabledController(browserGamepad) {
  74145. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74146. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74147. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74148. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74149. /**
  74150. * The device position in babylon space
  74151. */
  74152. _this.devicePosition = BABYLON.Vector3.Zero();
  74153. /**
  74154. * The device rotation in babylon space
  74155. */
  74156. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74157. /**
  74158. * The scale factor of the device in babylon space
  74159. */
  74160. _this.deviceScaleFactor = 1;
  74161. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74162. /**
  74163. * Internal, matrix used to convert room space to babylon space
  74164. * @hidden
  74165. */
  74166. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74167. /**
  74168. * Node to be used when casting a ray from the controller
  74169. * @hidden
  74170. */
  74171. _this._pointingPoseNode = null;
  74172. _this._workingMatrix = BABYLON.Matrix.Identity();
  74173. /**
  74174. * @hidden
  74175. */
  74176. _this._meshAttachedObservable = new BABYLON.Observable();
  74177. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74178. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74179. _this.position = BABYLON.Vector3.Zero();
  74180. _this.rotationQuaternion = new BABYLON.Quaternion();
  74181. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74182. _this._calculatedRotation = new BABYLON.Quaternion();
  74183. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74184. return _this;
  74185. }
  74186. /**
  74187. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74188. */
  74189. PoseEnabledController.prototype.update = function () {
  74190. _super.prototype.update.call(this);
  74191. this._updatePoseAndMesh();
  74192. };
  74193. /**
  74194. * Updates only the pose device and mesh without doing any button event checking
  74195. */
  74196. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74197. var pose = this.browserGamepad.pose;
  74198. this.updateFromDevice(pose);
  74199. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74200. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74201. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74202. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74203. if (this._mesh) {
  74204. this._mesh.position.copyFrom(this.devicePosition);
  74205. if (this._mesh.rotationQuaternion) {
  74206. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74207. }
  74208. }
  74209. };
  74210. /**
  74211. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74212. * @param poseData raw pose fromthe device
  74213. */
  74214. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74215. if (poseData) {
  74216. this.rawPose = poseData;
  74217. if (poseData.position) {
  74218. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74219. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74220. this._deviceRoomPosition.z *= -1;
  74221. }
  74222. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74223. this._calculatedPosition.addInPlace(this.position);
  74224. }
  74225. var pose = this.rawPose;
  74226. if (poseData.orientation && pose.orientation) {
  74227. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74228. if (this._mesh) {
  74229. if (this._mesh.getScene().useRightHandedSystem) {
  74230. this._deviceRoomRotationQuaternion.z *= -1;
  74231. this._deviceRoomRotationQuaternion.w *= -1;
  74232. }
  74233. else {
  74234. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74235. }
  74236. }
  74237. // if the camera is set, rotate to the camera's rotation
  74238. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74239. }
  74240. }
  74241. };
  74242. /**
  74243. * Attaches a mesh to the controller
  74244. * @param mesh the mesh to be attached
  74245. */
  74246. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74247. if (this._mesh) {
  74248. this._mesh.parent = null;
  74249. }
  74250. this._mesh = mesh;
  74251. if (this._poseControlledCamera) {
  74252. this._mesh.parent = this._poseControlledCamera;
  74253. }
  74254. if (!this._mesh.rotationQuaternion) {
  74255. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74256. }
  74257. // 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
  74258. this._updatePoseAndMesh();
  74259. if (this._pointingPoseNode) {
  74260. var parents = [];
  74261. var obj = this._pointingPoseNode;
  74262. while (obj.parent) {
  74263. parents.push(obj.parent);
  74264. obj = obj.parent;
  74265. }
  74266. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74267. }
  74268. this._meshAttachedObservable.notifyObservers(mesh);
  74269. };
  74270. /**
  74271. * Attaches the controllers mesh to a camera
  74272. * @param camera the camera the mesh should be attached to
  74273. */
  74274. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74275. this._poseControlledCamera = camera;
  74276. if (this._mesh) {
  74277. this._mesh.parent = this._poseControlledCamera;
  74278. }
  74279. };
  74280. /**
  74281. * Disposes of the controller
  74282. */
  74283. PoseEnabledController.prototype.dispose = function () {
  74284. if (this._mesh) {
  74285. this._mesh.dispose();
  74286. }
  74287. this._mesh = null;
  74288. _super.prototype.dispose.call(this);
  74289. };
  74290. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74291. /**
  74292. * The mesh that is attached to the controller
  74293. */
  74294. get: function () {
  74295. return this._mesh;
  74296. },
  74297. enumerable: true,
  74298. configurable: true
  74299. });
  74300. /**
  74301. * Gets the ray of the controller in the direction the controller is pointing
  74302. * @param length the length the resulting ray should be
  74303. * @returns a ray in the direction the controller is pointing
  74304. */
  74305. PoseEnabledController.prototype.getForwardRay = function (length) {
  74306. if (length === void 0) { length = 100; }
  74307. if (!this.mesh) {
  74308. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74309. }
  74310. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74311. var origin = m.getTranslation();
  74312. var forward = new BABYLON.Vector3(0, 0, -1);
  74313. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74314. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74315. return new BABYLON.Ray(origin, direction, length);
  74316. };
  74317. /**
  74318. * Name of the child mesh that can be used to cast a ray from the controller
  74319. */
  74320. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74321. return PoseEnabledController;
  74322. }(BABYLON.Gamepad));
  74323. BABYLON.PoseEnabledController = PoseEnabledController;
  74324. })(BABYLON || (BABYLON = {}));
  74325. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74326. var BABYLON;
  74327. (function (BABYLON) {
  74328. /**
  74329. * Defines the WebVRController object that represents controllers tracked in 3D space
  74330. */
  74331. var WebVRController = /** @class */ (function (_super) {
  74332. __extends(WebVRController, _super);
  74333. /**
  74334. * Creates a new WebVRController from a gamepad
  74335. * @param vrGamepad the gamepad that the WebVRController should be created from
  74336. */
  74337. function WebVRController(vrGamepad) {
  74338. var _this = _super.call(this, vrGamepad) || this;
  74339. // Observables
  74340. /**
  74341. * Fired when the trigger state has changed
  74342. */
  74343. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74344. /**
  74345. * Fired when the main button state has changed
  74346. */
  74347. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74348. /**
  74349. * Fired when the secondary button state has changed
  74350. */
  74351. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74352. /**
  74353. * Fired when the pad state has changed
  74354. */
  74355. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74356. /**
  74357. * Fired when controllers stick values have changed
  74358. */
  74359. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74360. /**
  74361. * X and Y axis corrisponding to the controllers joystick
  74362. */
  74363. _this.pad = { x: 0, y: 0 };
  74364. // avoid GC, store state in a tmp object
  74365. _this._changes = {
  74366. pressChanged: false,
  74367. touchChanged: false,
  74368. valueChanged: false,
  74369. changed: false
  74370. };
  74371. _this._buttons = new Array(vrGamepad.buttons.length);
  74372. _this.hand = vrGamepad.hand;
  74373. return _this;
  74374. }
  74375. /**
  74376. * Fired when a controller button's state has changed
  74377. * @param callback the callback containing the button that was modified
  74378. */
  74379. WebVRController.prototype.onButtonStateChange = function (callback) {
  74380. this._onButtonStateChange = callback;
  74381. };
  74382. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74383. /**
  74384. * The default controller model for the controller
  74385. */
  74386. get: function () {
  74387. return this._defaultModel;
  74388. },
  74389. enumerable: true,
  74390. configurable: true
  74391. });
  74392. /**
  74393. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74394. */
  74395. WebVRController.prototype.update = function () {
  74396. _super.prototype.update.call(this);
  74397. for (var index = 0; index < this._buttons.length; index++) {
  74398. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74399. }
  74400. ;
  74401. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74402. this.pad.x = this.leftStick.x;
  74403. this.pad.y = this.leftStick.y;
  74404. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74405. }
  74406. };
  74407. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74408. if (!newState) {
  74409. newState = {
  74410. pressed: false,
  74411. touched: false,
  74412. value: 0
  74413. };
  74414. }
  74415. if (!currentState) {
  74416. this._buttons[buttonIndex] = {
  74417. pressed: newState.pressed,
  74418. touched: newState.touched,
  74419. value: newState.value
  74420. };
  74421. return;
  74422. }
  74423. this._checkChanges(newState, currentState);
  74424. if (this._changes.changed) {
  74425. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74426. this._handleButtonChange(buttonIndex, newState, this._changes);
  74427. }
  74428. this._buttons[buttonIndex].pressed = newState.pressed;
  74429. this._buttons[buttonIndex].touched = newState.touched;
  74430. // oculus triggers are never 0, thou not touched.
  74431. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74432. };
  74433. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74434. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74435. this._changes.touchChanged = newState.touched !== currentState.touched;
  74436. this._changes.valueChanged = newState.value !== currentState.value;
  74437. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74438. return this._changes;
  74439. };
  74440. /**
  74441. * Disposes of th webVRCOntroller
  74442. */
  74443. WebVRController.prototype.dispose = function () {
  74444. _super.prototype.dispose.call(this);
  74445. this.onTriggerStateChangedObservable.clear();
  74446. this.onMainButtonStateChangedObservable.clear();
  74447. this.onSecondaryButtonStateChangedObservable.clear();
  74448. this.onPadStateChangedObservable.clear();
  74449. this.onPadValuesChangedObservable.clear();
  74450. };
  74451. return WebVRController;
  74452. }(BABYLON.PoseEnabledController));
  74453. BABYLON.WebVRController = WebVRController;
  74454. })(BABYLON || (BABYLON = {}));
  74455. //# sourceMappingURL=babylon.webVRController.js.map
  74456. var BABYLON;
  74457. (function (BABYLON) {
  74458. /**
  74459. * Oculus Touch Controller
  74460. */
  74461. var OculusTouchController = /** @class */ (function (_super) {
  74462. __extends(OculusTouchController, _super);
  74463. /**
  74464. * Creates a new OculusTouchController from a gamepad
  74465. * @param vrGamepad the gamepad that the controller should be created from
  74466. */
  74467. function OculusTouchController(vrGamepad) {
  74468. var _this = _super.call(this, vrGamepad) || this;
  74469. /**
  74470. * Fired when the secondary trigger on this controller is modified
  74471. */
  74472. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74473. /**
  74474. * Fired when the thumb rest on this controller is modified
  74475. */
  74476. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74477. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74478. return _this;
  74479. }
  74480. /**
  74481. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74482. * @param scene scene in which to add meshes
  74483. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74484. */
  74485. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74486. var _this = this;
  74487. var meshName;
  74488. // Hand
  74489. if (this.hand === 'left') {
  74490. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74491. }
  74492. else { // Right is the default if no hand is specified
  74493. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74494. }
  74495. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74496. /*
  74497. Parent Mesh name: oculus_touch_left
  74498. - body
  74499. - trigger
  74500. - thumbstick
  74501. - grip
  74502. - button_y
  74503. - button_x
  74504. - button_enter
  74505. */
  74506. _this._defaultModel = newMeshes[1];
  74507. _this.attachToMesh(_this._defaultModel);
  74508. if (meshLoaded) {
  74509. meshLoaded(_this._defaultModel);
  74510. }
  74511. });
  74512. };
  74513. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74514. /**
  74515. * Fired when the A button on this controller is modified
  74516. */
  74517. get: function () {
  74518. if (this.hand === 'right') {
  74519. return this.onMainButtonStateChangedObservable;
  74520. }
  74521. else {
  74522. throw new Error('No A button on left hand');
  74523. }
  74524. },
  74525. enumerable: true,
  74526. configurable: true
  74527. });
  74528. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74529. /**
  74530. * Fired when the B button on this controller is modified
  74531. */
  74532. get: function () {
  74533. if (this.hand === 'right') {
  74534. return this.onSecondaryButtonStateChangedObservable;
  74535. }
  74536. else {
  74537. throw new Error('No B button on left hand');
  74538. }
  74539. },
  74540. enumerable: true,
  74541. configurable: true
  74542. });
  74543. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74544. /**
  74545. * Fired when the X button on this controller is modified
  74546. */
  74547. get: function () {
  74548. if (this.hand === 'left') {
  74549. return this.onMainButtonStateChangedObservable;
  74550. }
  74551. else {
  74552. throw new Error('No X button on right hand');
  74553. }
  74554. },
  74555. enumerable: true,
  74556. configurable: true
  74557. });
  74558. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74559. /**
  74560. * Fired when the Y button on this controller is modified
  74561. */
  74562. get: function () {
  74563. if (this.hand === 'left') {
  74564. return this.onSecondaryButtonStateChangedObservable;
  74565. }
  74566. else {
  74567. throw new Error('No Y button on right hand');
  74568. }
  74569. },
  74570. enumerable: true,
  74571. configurable: true
  74572. });
  74573. /**
  74574. * Called once for each button that changed state since the last frame
  74575. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74576. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74577. * 2) secondary trigger (same)
  74578. * 3) A (right) X (left), touch, pressed = value
  74579. * 4) B / Y
  74580. * 5) thumb rest
  74581. * @param buttonIdx Which button index changed
  74582. * @param state New state of the button
  74583. * @param changes Which properties on the state changed since last frame
  74584. */
  74585. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74586. var notifyObject = state; //{ state: state, changes: changes };
  74587. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74588. switch (buttonIdx) {
  74589. case 0:
  74590. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74591. return;
  74592. case 1: // index trigger
  74593. if (this._defaultModel) {
  74594. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74595. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74596. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74597. }
  74598. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74599. return;
  74600. case 2: // secondary trigger
  74601. if (this._defaultModel) {
  74602. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74603. }
  74604. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74605. return;
  74606. case 3:
  74607. if (this._defaultModel) {
  74608. if (notifyObject.pressed) {
  74609. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74610. }
  74611. else {
  74612. (this._defaultModel.getChildren()[1]).position.y = 0;
  74613. }
  74614. }
  74615. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74616. return;
  74617. case 4:
  74618. if (this._defaultModel) {
  74619. if (notifyObject.pressed) {
  74620. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74621. }
  74622. else {
  74623. (this._defaultModel.getChildren()[2]).position.y = 0;
  74624. }
  74625. }
  74626. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74627. return;
  74628. case 5:
  74629. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74630. return;
  74631. }
  74632. };
  74633. /**
  74634. * Base Url for the controller model.
  74635. */
  74636. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74637. /**
  74638. * File name for the left controller model.
  74639. */
  74640. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74641. /**
  74642. * File name for the right controller model.
  74643. */
  74644. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74645. return OculusTouchController;
  74646. }(BABYLON.WebVRController));
  74647. BABYLON.OculusTouchController = OculusTouchController;
  74648. })(BABYLON || (BABYLON = {}));
  74649. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74650. var BABYLON;
  74651. (function (BABYLON) {
  74652. /**
  74653. * Vive Controller
  74654. */
  74655. var ViveController = /** @class */ (function (_super) {
  74656. __extends(ViveController, _super);
  74657. /**
  74658. * Creates a new ViveController from a gamepad
  74659. * @param vrGamepad the gamepad that the controller should be created from
  74660. */
  74661. function ViveController(vrGamepad) {
  74662. var _this = _super.call(this, vrGamepad) || this;
  74663. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74664. _this._invertLeftStickY = true;
  74665. return _this;
  74666. }
  74667. /**
  74668. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74669. * @param scene scene in which to add meshes
  74670. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74671. */
  74672. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74673. var _this = this;
  74674. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74675. /*
  74676. Parent Mesh name: ViveWand
  74677. - body
  74678. - r_gripper
  74679. - l_gripper
  74680. - menu_button
  74681. - system_button
  74682. - trackpad
  74683. - trigger
  74684. - LED
  74685. */
  74686. _this._defaultModel = newMeshes[1];
  74687. _this.attachToMesh(_this._defaultModel);
  74688. if (meshLoaded) {
  74689. meshLoaded(_this._defaultModel);
  74690. }
  74691. });
  74692. };
  74693. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74694. /**
  74695. * Fired when the left button on this controller is modified
  74696. */
  74697. get: function () {
  74698. return this.onMainButtonStateChangedObservable;
  74699. },
  74700. enumerable: true,
  74701. configurable: true
  74702. });
  74703. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74704. /**
  74705. * Fired when the right button on this controller is modified
  74706. */
  74707. get: function () {
  74708. return this.onMainButtonStateChangedObservable;
  74709. },
  74710. enumerable: true,
  74711. configurable: true
  74712. });
  74713. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  74714. /**
  74715. * Fired when the menu button on this controller is modified
  74716. */
  74717. get: function () {
  74718. return this.onSecondaryButtonStateChangedObservable;
  74719. },
  74720. enumerable: true,
  74721. configurable: true
  74722. });
  74723. /**
  74724. * Called once for each button that changed state since the last frame
  74725. * Vive mapping:
  74726. * 0: touchpad
  74727. * 1: trigger
  74728. * 2: left AND right buttons
  74729. * 3: menu button
  74730. * @param buttonIdx Which button index changed
  74731. * @param state New state of the button
  74732. * @param changes Which properties on the state changed since last frame
  74733. */
  74734. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74735. var notifyObject = state; //{ state: state, changes: changes };
  74736. switch (buttonIdx) {
  74737. case 0:
  74738. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74739. return;
  74740. case 1: // index trigger
  74741. if (this._defaultModel) {
  74742. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  74743. }
  74744. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74745. return;
  74746. case 2: // left AND right button
  74747. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74748. return;
  74749. case 3:
  74750. if (this._defaultModel) {
  74751. if (notifyObject.pressed) {
  74752. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74753. }
  74754. else {
  74755. (this._defaultModel.getChildren()[2]).position.y = 0;
  74756. }
  74757. }
  74758. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74759. return;
  74760. }
  74761. };
  74762. /**
  74763. * Base Url for the controller model.
  74764. */
  74765. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  74766. /**
  74767. * File name for the controller model.
  74768. */
  74769. ViveController.MODEL_FILENAME = 'wand.babylon';
  74770. return ViveController;
  74771. }(BABYLON.WebVRController));
  74772. BABYLON.ViveController = ViveController;
  74773. })(BABYLON || (BABYLON = {}));
  74774. //# sourceMappingURL=babylon.viveController.js.map
  74775. var BABYLON;
  74776. (function (BABYLON) {
  74777. /**
  74778. * Generic Controller
  74779. */
  74780. var GenericController = /** @class */ (function (_super) {
  74781. __extends(GenericController, _super);
  74782. /**
  74783. * Creates a new GenericController from a gamepad
  74784. * @param vrGamepad the gamepad that the controller should be created from
  74785. */
  74786. function GenericController(vrGamepad) {
  74787. return _super.call(this, vrGamepad) || this;
  74788. }
  74789. /**
  74790. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74791. * @param scene scene in which to add meshes
  74792. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74793. */
  74794. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74795. var _this = this;
  74796. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  74797. _this._defaultModel = newMeshes[1];
  74798. _this.attachToMesh(_this._defaultModel);
  74799. if (meshLoaded) {
  74800. meshLoaded(_this._defaultModel);
  74801. }
  74802. });
  74803. };
  74804. /**
  74805. * Called once for each button that changed state since the last frame
  74806. * @param buttonIdx Which button index changed
  74807. * @param state New state of the button
  74808. * @param changes Which properties on the state changed since last frame
  74809. */
  74810. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74811. console.log("Button id: " + buttonIdx + "state: ");
  74812. console.dir(state);
  74813. };
  74814. /**
  74815. * Base Url for the controller model.
  74816. */
  74817. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74818. /**
  74819. * File name for the controller model.
  74820. */
  74821. GenericController.MODEL_FILENAME = 'generic.babylon';
  74822. return GenericController;
  74823. }(BABYLON.WebVRController));
  74824. BABYLON.GenericController = GenericController;
  74825. })(BABYLON || (BABYLON = {}));
  74826. //# sourceMappingURL=babylon.genericController.js.map
  74827. var BABYLON;
  74828. (function (BABYLON) {
  74829. /**
  74830. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  74831. */
  74832. var LoadedMeshInfo = /** @class */ (function () {
  74833. function LoadedMeshInfo() {
  74834. /**
  74835. * Map of the button meshes contained in the controller
  74836. */
  74837. this.buttonMeshes = {};
  74838. /**
  74839. * Map of the axis meshes contained in the controller
  74840. */
  74841. this.axisMeshes = {};
  74842. }
  74843. return LoadedMeshInfo;
  74844. }());
  74845. /**
  74846. * Defines the WindowsMotionController object that the state of the windows motion controller
  74847. */
  74848. var WindowsMotionController = /** @class */ (function (_super) {
  74849. __extends(WindowsMotionController, _super);
  74850. /**
  74851. * Creates a new WindowsMotionController from a gamepad
  74852. * @param vrGamepad the gamepad that the controller should be created from
  74853. */
  74854. function WindowsMotionController(vrGamepad) {
  74855. var _this = _super.call(this, vrGamepad) || this;
  74856. _this._mapping = {
  74857. // Semantic button names
  74858. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  74859. // A mapping of the button name to glTF model node name
  74860. // that should be transformed by button value.
  74861. buttonMeshNames: {
  74862. 'trigger': 'SELECT',
  74863. 'menu': 'MENU',
  74864. 'grip': 'GRASP',
  74865. 'thumbstick': 'THUMBSTICK_PRESS',
  74866. 'trackpad': 'TOUCHPAD_PRESS'
  74867. },
  74868. // This mapping is used to translate from the Motion Controller to Babylon semantics
  74869. buttonObservableNames: {
  74870. 'trigger': 'onTriggerStateChangedObservable',
  74871. 'menu': 'onSecondaryButtonStateChangedObservable',
  74872. 'grip': 'onMainButtonStateChangedObservable',
  74873. 'thumbstick': 'onPadStateChangedObservable',
  74874. 'trackpad': 'onTrackpadChangedObservable'
  74875. },
  74876. // A mapping of the axis name to glTF model node name
  74877. // that should be transformed by axis value.
  74878. // This array mirrors the browserGamepad.axes array, such that
  74879. // the mesh corresponding to axis 0 is in this array index 0.
  74880. axisMeshNames: [
  74881. 'THUMBSTICK_X',
  74882. 'THUMBSTICK_Y',
  74883. 'TOUCHPAD_TOUCH_X',
  74884. 'TOUCHPAD_TOUCH_Y'
  74885. ],
  74886. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  74887. };
  74888. /**
  74889. * Fired when the trackpad on this controller is clicked
  74890. */
  74891. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  74892. /**
  74893. * Fired when the trackpad on this controller is modified
  74894. */
  74895. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  74896. /**
  74897. * The current x and y values of this controller's trackpad
  74898. */
  74899. _this.trackpad = { x: 0, y: 0 };
  74900. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  74901. _this._loadedMeshInfo = null;
  74902. return _this;
  74903. }
  74904. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  74905. /**
  74906. * Fired when the trigger on this controller is modified
  74907. */
  74908. get: function () {
  74909. return this.onTriggerStateChangedObservable;
  74910. },
  74911. enumerable: true,
  74912. configurable: true
  74913. });
  74914. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  74915. /**
  74916. * Fired when the menu button on this controller is modified
  74917. */
  74918. get: function () {
  74919. return this.onSecondaryButtonStateChangedObservable;
  74920. },
  74921. enumerable: true,
  74922. configurable: true
  74923. });
  74924. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  74925. /**
  74926. * Fired when the grip button on this controller is modified
  74927. */
  74928. get: function () {
  74929. return this.onMainButtonStateChangedObservable;
  74930. },
  74931. enumerable: true,
  74932. configurable: true
  74933. });
  74934. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  74935. /**
  74936. * Fired when the thumbstick button on this controller is modified
  74937. */
  74938. get: function () {
  74939. return this.onPadStateChangedObservable;
  74940. },
  74941. enumerable: true,
  74942. configurable: true
  74943. });
  74944. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  74945. /**
  74946. * Fired when the touchpad button on this controller is modified
  74947. */
  74948. get: function () {
  74949. return this.onTrackpadChangedObservable;
  74950. },
  74951. enumerable: true,
  74952. configurable: true
  74953. });
  74954. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  74955. /**
  74956. * Fired when the touchpad values on this controller are modified
  74957. */
  74958. get: function () {
  74959. return this.onTrackpadValuesChangedObservable;
  74960. },
  74961. enumerable: true,
  74962. configurable: true
  74963. });
  74964. WindowsMotionController.prototype._updateTrackpad = function () {
  74965. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  74966. this.trackpad.x = this.browserGamepad["axes"][2];
  74967. this.trackpad.y = this.browserGamepad["axes"][3];
  74968. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  74969. }
  74970. };
  74971. /**
  74972. * Called once per frame by the engine.
  74973. */
  74974. WindowsMotionController.prototype.update = function () {
  74975. _super.prototype.update.call(this);
  74976. if (this.browserGamepad.axes) {
  74977. this._updateTrackpad();
  74978. // Only need to animate axes if there is a loaded mesh
  74979. if (this._loadedMeshInfo) {
  74980. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  74981. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  74982. }
  74983. }
  74984. }
  74985. };
  74986. /**
  74987. * Called once for each button that changed state since the last frame
  74988. * @param buttonIdx Which button index changed
  74989. * @param state New state of the button
  74990. * @param changes Which properties on the state changed since last frame
  74991. */
  74992. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74993. var buttonName = this._mapping.buttons[buttonIdx];
  74994. if (!buttonName) {
  74995. return;
  74996. }
  74997. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  74998. this._updateTrackpad();
  74999. // Only emit events for buttons that we know how to map from index to name
  75000. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75001. if (observable) {
  75002. observable.notifyObservers(state);
  75003. }
  75004. this._lerpButtonTransform(buttonName, state.value);
  75005. };
  75006. /**
  75007. * Moves the buttons on the controller mesh based on their current state
  75008. * @param buttonName the name of the button to move
  75009. * @param buttonValue the value of the button which determines the buttons new position
  75010. */
  75011. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75012. // If there is no loaded mesh, there is nothing to transform.
  75013. if (!this._loadedMeshInfo) {
  75014. return;
  75015. }
  75016. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75017. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75018. return;
  75019. }
  75020. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75021. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75022. };
  75023. /**
  75024. * Moves the axis on the controller mesh based on its current state
  75025. * @param axis the index of the axis
  75026. * @param axisValue the value of the axis which determines the meshes new position
  75027. * @hidden
  75028. */
  75029. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75030. if (!this._loadedMeshInfo) {
  75031. return;
  75032. }
  75033. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75034. if (!meshInfo) {
  75035. return;
  75036. }
  75037. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75038. return;
  75039. }
  75040. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75041. var lerpValue = axisValue * 0.5 + 0.5;
  75042. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75043. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75044. };
  75045. /**
  75046. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75047. * @param scene scene in which to add meshes
  75048. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75049. */
  75050. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75051. var _this = this;
  75052. if (forceDefault === void 0) { forceDefault = false; }
  75053. var path;
  75054. var filename;
  75055. // Checking if GLB loader is present
  75056. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75057. // Determine the device specific folder based on the ID suffix
  75058. var device = 'default';
  75059. if (this.id && !forceDefault) {
  75060. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75061. device = ((match && match[0]) || device);
  75062. }
  75063. // Hand
  75064. if (this.hand === 'left') {
  75065. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75066. }
  75067. else { // Right is the default if no hand is specified
  75068. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75069. }
  75070. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75071. }
  75072. else {
  75073. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75074. path = BABYLON.GenericController.MODEL_BASE_URL;
  75075. filename = BABYLON.GenericController.MODEL_FILENAME;
  75076. }
  75077. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75078. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75079. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75080. if (!_this._loadedMeshInfo) {
  75081. return;
  75082. }
  75083. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75084. _this.attachToMesh(_this._defaultModel);
  75085. if (meshLoaded) {
  75086. meshLoaded(_this._defaultModel);
  75087. }
  75088. }, null, function (scene, message) {
  75089. BABYLON.Tools.Log(message);
  75090. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75091. if (!forceDefault) {
  75092. _this.initControllerMesh(scene, meshLoaded, true);
  75093. }
  75094. });
  75095. };
  75096. /**
  75097. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75098. * can be transformed by button presses and axes values, based on this._mapping.
  75099. *
  75100. * @param scene scene in which the meshes exist
  75101. * @param meshes list of meshes that make up the controller model to process
  75102. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75103. */
  75104. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75105. var loadedMeshInfo = null;
  75106. // Create a new mesh to contain the glTF hierarchy
  75107. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75108. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75109. var childMesh = null;
  75110. for (var i = 0; i < meshes.length; i++) {
  75111. var mesh = meshes[i];
  75112. if (!mesh.parent) {
  75113. // Exclude controller meshes from picking results
  75114. mesh.isPickable = false;
  75115. // Handle root node, attach to the new parentMesh
  75116. childMesh = mesh;
  75117. break;
  75118. }
  75119. }
  75120. if (childMesh) {
  75121. childMesh.setParent(parentMesh);
  75122. // Create our mesh info. Note that this method will always return non-null.
  75123. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75124. }
  75125. else {
  75126. BABYLON.Tools.Warn('Could not find root node in model file.');
  75127. }
  75128. return loadedMeshInfo;
  75129. };
  75130. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75131. var loadedMeshInfo = new LoadedMeshInfo();
  75132. var i;
  75133. loadedMeshInfo.rootNode = rootNode;
  75134. // Reset the caches
  75135. loadedMeshInfo.buttonMeshes = {};
  75136. loadedMeshInfo.axisMeshes = {};
  75137. // Button Meshes
  75138. for (i = 0; i < this._mapping.buttons.length; i++) {
  75139. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75140. if (!buttonMeshName) {
  75141. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75142. continue;
  75143. }
  75144. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75145. if (!buttonMesh) {
  75146. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75147. continue;
  75148. }
  75149. var buttonMeshInfo = {
  75150. index: i,
  75151. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75152. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75153. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75154. };
  75155. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75156. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75157. }
  75158. else {
  75159. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75160. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75161. '(VALUE: ' + !!buttonMeshInfo.value +
  75162. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75163. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75164. ')');
  75165. }
  75166. }
  75167. // Axis Meshes
  75168. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75169. var axisMeshName = this._mapping.axisMeshNames[i];
  75170. if (!axisMeshName) {
  75171. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75172. continue;
  75173. }
  75174. var axisMesh = getChildByName(rootNode, axisMeshName);
  75175. if (!axisMesh) {
  75176. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75177. continue;
  75178. }
  75179. var axisMeshInfo = {
  75180. index: i,
  75181. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75182. min: getImmediateChildByName(axisMesh, 'MIN'),
  75183. max: getImmediateChildByName(axisMesh, 'MAX')
  75184. };
  75185. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75186. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75187. }
  75188. else {
  75189. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75190. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75191. '(VALUE: ' + !!axisMeshInfo.value +
  75192. ', MIN: ' + !!axisMeshInfo.min +
  75193. ', MAX:' + !!axisMeshInfo.max +
  75194. ')');
  75195. }
  75196. }
  75197. // Pointing Ray
  75198. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75199. if (!loadedMeshInfo.pointingPoseNode) {
  75200. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75201. }
  75202. else {
  75203. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75204. }
  75205. return loadedMeshInfo;
  75206. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75207. function getChildByName(node, name) {
  75208. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75209. }
  75210. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75211. function getImmediateChildByName(node, name) {
  75212. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75213. }
  75214. };
  75215. /**
  75216. * Gets the ray of the controller in the direction the controller is pointing
  75217. * @param length the length the resulting ray should be
  75218. * @returns a ray in the direction the controller is pointing
  75219. */
  75220. WindowsMotionController.prototype.getForwardRay = function (length) {
  75221. if (length === void 0) { length = 100; }
  75222. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75223. return _super.prototype.getForwardRay.call(this, length);
  75224. }
  75225. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75226. var origin = m.getTranslation();
  75227. var forward = new BABYLON.Vector3(0, 0, -1);
  75228. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75229. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75230. return new BABYLON.Ray(origin, direction, length);
  75231. };
  75232. /**
  75233. * Disposes of the controller
  75234. */
  75235. WindowsMotionController.prototype.dispose = function () {
  75236. _super.prototype.dispose.call(this);
  75237. this.onTrackpadChangedObservable.clear();
  75238. };
  75239. /**
  75240. * The base url used to load the left and right controller models
  75241. */
  75242. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75243. /**
  75244. * The name of the left controller model file
  75245. */
  75246. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75247. /**
  75248. * The name of the right controller model file
  75249. */
  75250. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75251. /**
  75252. * The controller name prefix for this controller type
  75253. */
  75254. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75255. /**
  75256. * The controller id pattern for this controller type
  75257. */
  75258. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75259. return WindowsMotionController;
  75260. }(BABYLON.WebVRController));
  75261. BABYLON.WindowsMotionController = WindowsMotionController;
  75262. })(BABYLON || (BABYLON = {}));
  75263. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75264. var BABYLON;
  75265. (function (BABYLON) {
  75266. /**
  75267. * Gear VR Controller
  75268. */
  75269. var GearVRController = /** @class */ (function (_super) {
  75270. __extends(GearVRController, _super);
  75271. /**
  75272. * Creates a new GearVRController from a gamepad
  75273. * @param vrGamepad the gamepad that the controller should be created from
  75274. */
  75275. function GearVRController(vrGamepad) {
  75276. var _this = _super.call(this, vrGamepad) || this;
  75277. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75278. _this._draggedRoomRotation = 0;
  75279. _this._tmpVector = new BABYLON.Vector3();
  75280. _this._buttonIndexToObservableNameMap = [
  75281. 'onTrackpadChangedObservable',
  75282. 'onTriggerStateChangedObservable' // Trigger
  75283. ];
  75284. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75285. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75286. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75287. return _this;
  75288. }
  75289. /**
  75290. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75291. * @param poseData raw pose fromthe device
  75292. */
  75293. GearVRController.prototype.updateFromDevice = function (poseData) {
  75294. _super.prototype.updateFromDevice.call(this, poseData);
  75295. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75296. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75297. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75298. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75299. // Find the radian distance away that the headset is from the controllers rotation
  75300. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75301. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75302. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75303. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75304. this._draggedRoomRotation += rotationAmount;
  75305. // Rotate controller around headset
  75306. var sin = Math.sin(-rotationAmount);
  75307. var cos = Math.cos(-rotationAmount);
  75308. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75309. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75310. }
  75311. }
  75312. }
  75313. };
  75314. /**
  75315. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75316. * @param scene scene in which to add meshes
  75317. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75318. */
  75319. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75320. var _this = this;
  75321. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75322. // Offset the controller so it will rotate around the users wrist
  75323. var mesh = new BABYLON.Mesh("", scene);
  75324. newMeshes[1].parent = mesh;
  75325. newMeshes[1].position.z = -0.15;
  75326. _this._defaultModel = mesh;
  75327. _this.attachToMesh(_this._defaultModel);
  75328. if (meshLoaded) {
  75329. meshLoaded(_this._defaultModel);
  75330. }
  75331. });
  75332. };
  75333. /**
  75334. * Called once for each button that changed state since the last frame
  75335. * @param buttonIdx Which button index changed
  75336. * @param state New state of the button
  75337. * @param changes Which properties on the state changed since last frame
  75338. */
  75339. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75340. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75341. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75342. // Only emit events for buttons that we know how to map from index to observable
  75343. var observable = this[observableName];
  75344. if (observable) {
  75345. observable.notifyObservers(state);
  75346. }
  75347. }
  75348. };
  75349. /**
  75350. * Base Url for the controller model.
  75351. */
  75352. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75353. /**
  75354. * File name for the controller model.
  75355. */
  75356. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75357. /**
  75358. * Gamepad Id prefix used to identify this controller.
  75359. */
  75360. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75361. return GearVRController;
  75362. }(BABYLON.WebVRController));
  75363. BABYLON.GearVRController = GearVRController;
  75364. })(BABYLON || (BABYLON = {}));
  75365. //# sourceMappingURL=babylon.gearVRController.js.map
  75366. var BABYLON;
  75367. (function (BABYLON) {
  75368. /**
  75369. * Google Daydream controller
  75370. */
  75371. var DaydreamController = /** @class */ (function (_super) {
  75372. __extends(DaydreamController, _super);
  75373. /**
  75374. * Creates a new DaydreamController from a gamepad
  75375. * @param vrGamepad the gamepad that the controller should be created from
  75376. */
  75377. function DaydreamController(vrGamepad) {
  75378. var _this = _super.call(this, vrGamepad) || this;
  75379. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75380. return _this;
  75381. }
  75382. /**
  75383. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75384. * @param scene scene in which to add meshes
  75385. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75386. */
  75387. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75388. var _this = this;
  75389. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75390. _this._defaultModel = newMeshes[1];
  75391. _this.attachToMesh(_this._defaultModel);
  75392. if (meshLoaded) {
  75393. meshLoaded(_this._defaultModel);
  75394. }
  75395. });
  75396. };
  75397. /**
  75398. * Called once for each button that changed state since the last frame
  75399. * @param buttonIdx Which button index changed
  75400. * @param state New state of the button
  75401. * @param changes Which properties on the state changed since last frame
  75402. */
  75403. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75404. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75405. if (buttonIdx === 0) {
  75406. var observable = this.onTriggerStateChangedObservable;
  75407. if (observable) {
  75408. observable.notifyObservers(state);
  75409. }
  75410. }
  75411. else {
  75412. // If the app or home buttons are ever made available
  75413. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75414. }
  75415. };
  75416. /**
  75417. * Base Url for the controller model.
  75418. */
  75419. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75420. /**
  75421. * File name for the controller model.
  75422. */
  75423. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75424. /**
  75425. * Gamepad Id prefix used to identify Daydream Controller.
  75426. */
  75427. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75428. return DaydreamController;
  75429. }(BABYLON.WebVRController));
  75430. BABYLON.DaydreamController = DaydreamController;
  75431. })(BABYLON || (BABYLON = {}));
  75432. //# sourceMappingURL=babylon.daydreamController.js.map
  75433. var BABYLON;
  75434. (function (BABYLON) {
  75435. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75436. get: function () {
  75437. if (!this._gamepadManager) {
  75438. this._gamepadManager = new BABYLON.GamepadManager(this);
  75439. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75440. if (!component) {
  75441. component = new GamepadSystemSceneComponent(this);
  75442. this._addComponent(component);
  75443. }
  75444. }
  75445. return this._gamepadManager;
  75446. },
  75447. enumerable: true,
  75448. configurable: true
  75449. });
  75450. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75451. this.add(new BABYLON.FreeCameraGamepadInput());
  75452. return this;
  75453. };
  75454. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75455. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75456. return this;
  75457. };
  75458. /**
  75459. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75460. */
  75461. var GamepadSystemSceneComponent = /** @class */ (function () {
  75462. /**
  75463. * Creates a new instance of the component for the given scene
  75464. * @param scene Defines the scene to register the component in
  75465. */
  75466. function GamepadSystemSceneComponent(scene) {
  75467. /**
  75468. * The component name helpfull to identify the component in the list of scene components.
  75469. */
  75470. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75471. this.scene = scene;
  75472. }
  75473. /**
  75474. * Registers the component in a given scene
  75475. */
  75476. GamepadSystemSceneComponent.prototype.register = function () {
  75477. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75478. };
  75479. /**
  75480. * Rebuilds the elements related to this component in case of
  75481. * context lost for instance.
  75482. */
  75483. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75484. // Nothing to do for gamepads
  75485. };
  75486. /**
  75487. * Disposes the component and the associated ressources
  75488. */
  75489. GamepadSystemSceneComponent.prototype.dispose = function () {
  75490. var gamepadManager = this.scene._gamepadManager;
  75491. if (gamepadManager) {
  75492. gamepadManager.dispose();
  75493. this.scene._gamepadManager = null;
  75494. }
  75495. };
  75496. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75497. var gamepadManager = this.scene._gamepadManager;
  75498. if (gamepadManager && gamepadManager._isMonitoring) {
  75499. gamepadManager._checkGamepadsStatus();
  75500. }
  75501. };
  75502. return GamepadSystemSceneComponent;
  75503. }());
  75504. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75505. })(BABYLON || (BABYLON = {}));
  75506. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75507. var BABYLON;
  75508. (function (BABYLON) {
  75509. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75510. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75511. });
  75512. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75513. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75514. });
  75515. var FollowCamera = /** @class */ (function (_super) {
  75516. __extends(FollowCamera, _super);
  75517. function FollowCamera(name, position, scene, lockedTarget) {
  75518. if (lockedTarget === void 0) { lockedTarget = null; }
  75519. var _this = _super.call(this, name, position, scene) || this;
  75520. _this.radius = 12;
  75521. _this.rotationOffset = 0;
  75522. _this.heightOffset = 4;
  75523. _this.cameraAcceleration = 0.05;
  75524. _this.maxCameraSpeed = 20;
  75525. _this.lockedTarget = lockedTarget;
  75526. return _this;
  75527. }
  75528. FollowCamera.prototype.getRadians = function (degrees) {
  75529. return degrees * Math.PI / 180;
  75530. };
  75531. FollowCamera.prototype.follow = function (cameraTarget) {
  75532. if (!cameraTarget)
  75533. return;
  75534. var yRotation;
  75535. if (cameraTarget.rotationQuaternion) {
  75536. var rotMatrix = new BABYLON.Matrix();
  75537. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75538. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75539. }
  75540. else {
  75541. yRotation = cameraTarget.rotation.y;
  75542. }
  75543. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75544. var targetPosition = cameraTarget.getAbsolutePosition();
  75545. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75546. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75547. var dx = targetX - this.position.x;
  75548. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75549. var dz = (targetZ) - this.position.z;
  75550. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75551. var vy = dy * this.cameraAcceleration;
  75552. var vz = dz * this.cameraAcceleration * 2;
  75553. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75554. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75555. }
  75556. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75557. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75558. }
  75559. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75560. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75561. }
  75562. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75563. this.setTarget(targetPosition);
  75564. };
  75565. /** @hidden */
  75566. FollowCamera.prototype._checkInputs = function () {
  75567. _super.prototype._checkInputs.call(this);
  75568. if (this.lockedTarget) {
  75569. this.follow(this.lockedTarget);
  75570. }
  75571. };
  75572. FollowCamera.prototype.getClassName = function () {
  75573. return "FollowCamera";
  75574. };
  75575. __decorate([
  75576. BABYLON.serialize()
  75577. ], FollowCamera.prototype, "radius", void 0);
  75578. __decorate([
  75579. BABYLON.serialize()
  75580. ], FollowCamera.prototype, "rotationOffset", void 0);
  75581. __decorate([
  75582. BABYLON.serialize()
  75583. ], FollowCamera.prototype, "heightOffset", void 0);
  75584. __decorate([
  75585. BABYLON.serialize()
  75586. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75587. __decorate([
  75588. BABYLON.serialize()
  75589. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75590. __decorate([
  75591. BABYLON.serializeAsMeshReference("lockedTargetId")
  75592. ], FollowCamera.prototype, "lockedTarget", void 0);
  75593. return FollowCamera;
  75594. }(BABYLON.TargetCamera));
  75595. BABYLON.FollowCamera = FollowCamera;
  75596. var ArcFollowCamera = /** @class */ (function (_super) {
  75597. __extends(ArcFollowCamera, _super);
  75598. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75599. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75600. _this.alpha = alpha;
  75601. _this.beta = beta;
  75602. _this.radius = radius;
  75603. _this.target = target;
  75604. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75605. _this.follow();
  75606. return _this;
  75607. }
  75608. ArcFollowCamera.prototype.follow = function () {
  75609. if (!this.target) {
  75610. return;
  75611. }
  75612. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75613. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75614. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75615. var targetPosition = this.target.getAbsolutePosition();
  75616. this.position = targetPosition.add(this._cartesianCoordinates);
  75617. this.setTarget(targetPosition);
  75618. };
  75619. /** @hidden */
  75620. ArcFollowCamera.prototype._checkInputs = function () {
  75621. _super.prototype._checkInputs.call(this);
  75622. this.follow();
  75623. };
  75624. ArcFollowCamera.prototype.getClassName = function () {
  75625. return "ArcFollowCamera";
  75626. };
  75627. return ArcFollowCamera;
  75628. }(BABYLON.TargetCamera));
  75629. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75630. })(BABYLON || (BABYLON = {}));
  75631. //# sourceMappingURL=babylon.followCamera.js.map
  75632. var BABYLON;
  75633. (function (BABYLON) {
  75634. // We're mainly based on the logic defined into the FreeCamera code
  75635. var UniversalCamera = /** @class */ (function (_super) {
  75636. __extends(UniversalCamera, _super);
  75637. //-- end properties for backward compatibility for inputs
  75638. function UniversalCamera(name, position, scene) {
  75639. var _this = _super.call(this, name, position, scene) || this;
  75640. _this.inputs.addGamepad();
  75641. return _this;
  75642. }
  75643. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75644. //-- Begin properties for backward compatibility for inputs
  75645. get: function () {
  75646. var gamepad = this.inputs.attached["gamepad"];
  75647. if (gamepad)
  75648. return gamepad.gamepadAngularSensibility;
  75649. return 0;
  75650. },
  75651. set: function (value) {
  75652. var gamepad = this.inputs.attached["gamepad"];
  75653. if (gamepad)
  75654. gamepad.gamepadAngularSensibility = value;
  75655. },
  75656. enumerable: true,
  75657. configurable: true
  75658. });
  75659. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75660. get: function () {
  75661. var gamepad = this.inputs.attached["gamepad"];
  75662. if (gamepad)
  75663. return gamepad.gamepadMoveSensibility;
  75664. return 0;
  75665. },
  75666. set: function (value) {
  75667. var gamepad = this.inputs.attached["gamepad"];
  75668. if (gamepad)
  75669. gamepad.gamepadMoveSensibility = value;
  75670. },
  75671. enumerable: true,
  75672. configurable: true
  75673. });
  75674. UniversalCamera.prototype.getClassName = function () {
  75675. return "UniversalCamera";
  75676. };
  75677. return UniversalCamera;
  75678. }(BABYLON.TouchCamera));
  75679. BABYLON.UniversalCamera = UniversalCamera;
  75680. })(BABYLON || (BABYLON = {}));
  75681. //# sourceMappingURL=babylon.universalCamera.js.map
  75682. var BABYLON;
  75683. (function (BABYLON) {
  75684. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75685. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75686. });
  75687. // We're mainly based on the logic defined into the FreeCamera code
  75688. var GamepadCamera = /** @class */ (function (_super) {
  75689. __extends(GamepadCamera, _super);
  75690. //-- end properties for backward compatibility for inputs
  75691. function GamepadCamera(name, position, scene) {
  75692. return _super.call(this, name, position, scene) || this;
  75693. }
  75694. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75695. //-- Begin properties for backward compatibility for inputs
  75696. get: function () {
  75697. var gamepad = this.inputs.attached["gamepad"];
  75698. if (gamepad)
  75699. return gamepad.gamepadAngularSensibility;
  75700. return 0;
  75701. },
  75702. set: function (value) {
  75703. var gamepad = this.inputs.attached["gamepad"];
  75704. if (gamepad)
  75705. gamepad.gamepadAngularSensibility = value;
  75706. },
  75707. enumerable: true,
  75708. configurable: true
  75709. });
  75710. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  75711. get: function () {
  75712. var gamepad = this.inputs.attached["gamepad"];
  75713. if (gamepad)
  75714. return gamepad.gamepadMoveSensibility;
  75715. return 0;
  75716. },
  75717. set: function (value) {
  75718. var gamepad = this.inputs.attached["gamepad"];
  75719. if (gamepad)
  75720. gamepad.gamepadMoveSensibility = value;
  75721. },
  75722. enumerable: true,
  75723. configurable: true
  75724. });
  75725. GamepadCamera.prototype.getClassName = function () {
  75726. return "GamepadCamera";
  75727. };
  75728. return GamepadCamera;
  75729. }(BABYLON.UniversalCamera));
  75730. BABYLON.GamepadCamera = GamepadCamera;
  75731. })(BABYLON || (BABYLON = {}));
  75732. //# sourceMappingURL=babylon.gamepadCamera.js.map
  75733. var BABYLON;
  75734. (function (BABYLON) {
  75735. var PostProcessRenderPipelineManager = /** @class */ (function () {
  75736. function PostProcessRenderPipelineManager() {
  75737. this._renderPipelines = {};
  75738. }
  75739. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  75740. this._renderPipelines[renderPipeline._name] = renderPipeline;
  75741. };
  75742. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  75743. if (unique === void 0) { unique = false; }
  75744. var renderPipeline = this._renderPipelines[renderPipelineName];
  75745. if (!renderPipeline) {
  75746. return;
  75747. }
  75748. renderPipeline._attachCameras(cameras, unique);
  75749. };
  75750. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  75751. var renderPipeline = this._renderPipelines[renderPipelineName];
  75752. if (!renderPipeline) {
  75753. return;
  75754. }
  75755. renderPipeline._detachCameras(cameras);
  75756. };
  75757. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75758. var renderPipeline = this._renderPipelines[renderPipelineName];
  75759. if (!renderPipeline) {
  75760. return;
  75761. }
  75762. renderPipeline._enableEffect(renderEffectName, cameras);
  75763. };
  75764. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75765. var renderPipeline = this._renderPipelines[renderPipelineName];
  75766. if (!renderPipeline) {
  75767. return;
  75768. }
  75769. renderPipeline._disableEffect(renderEffectName, cameras);
  75770. };
  75771. PostProcessRenderPipelineManager.prototype.update = function () {
  75772. for (var renderPipelineName in this._renderPipelines) {
  75773. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75774. var pipeline = this._renderPipelines[renderPipelineName];
  75775. if (!pipeline.isSupported) {
  75776. pipeline.dispose();
  75777. delete this._renderPipelines[renderPipelineName];
  75778. }
  75779. else {
  75780. pipeline._update();
  75781. }
  75782. }
  75783. }
  75784. };
  75785. /** @hidden */
  75786. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  75787. for (var renderPipelineName in this._renderPipelines) {
  75788. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75789. var pipeline = this._renderPipelines[renderPipelineName];
  75790. pipeline._rebuild();
  75791. }
  75792. }
  75793. };
  75794. PostProcessRenderPipelineManager.prototype.dispose = function () {
  75795. for (var renderPipelineName in this._renderPipelines) {
  75796. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75797. var pipeline = this._renderPipelines[renderPipelineName];
  75798. pipeline.dispose();
  75799. }
  75800. }
  75801. };
  75802. return PostProcessRenderPipelineManager;
  75803. }());
  75804. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  75805. })(BABYLON || (BABYLON = {}));
  75806. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  75807. var BABYLON;
  75808. (function (BABYLON) {
  75809. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  75810. get: function () {
  75811. if (!this._postProcessRenderPipelineManager) {
  75812. // Register the G Buffer component to the scene.
  75813. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  75814. if (!component) {
  75815. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  75816. this._addComponent(component);
  75817. }
  75818. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  75819. }
  75820. return this._postProcessRenderPipelineManager;
  75821. },
  75822. enumerable: true,
  75823. configurable: true
  75824. });
  75825. /**
  75826. * Defines the Render Pipeline scene component responsible to rendering pipelines
  75827. */
  75828. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  75829. /**
  75830. * Creates a new instance of the component for the given scene
  75831. * @param scene Defines the scene to register the component in
  75832. */
  75833. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  75834. /**
  75835. * The component name helpfull to identify the component in the list of scene components.
  75836. */
  75837. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  75838. this.scene = scene;
  75839. }
  75840. /**
  75841. * Registers the component in a given scene
  75842. */
  75843. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  75844. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  75845. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  75846. };
  75847. /**
  75848. * Rebuilds the elements related to this component in case of
  75849. * context lost for instance.
  75850. */
  75851. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  75852. // Nothing to do for this component
  75853. };
  75854. /**
  75855. * Disposes the component and the associated ressources
  75856. */
  75857. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  75858. if (this.scene._postProcessRenderPipelineManager) {
  75859. this.scene._postProcessRenderPipelineManager.dispose();
  75860. }
  75861. };
  75862. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75863. if (this.scene._postProcessRenderPipelineManager) {
  75864. this.scene._postProcessRenderPipelineManager.update();
  75865. }
  75866. };
  75867. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  75868. if (this.scene._postProcessRenderPipelineManager) {
  75869. this.scene._postProcessRenderPipelineManager._rebuild();
  75870. }
  75871. };
  75872. return PostProcessRenderPipelineManagerSceneComponent;
  75873. }());
  75874. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  75875. })(BABYLON || (BABYLON = {}));
  75876. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  75877. var BABYLON;
  75878. (function (BABYLON) {
  75879. /**
  75880. * This represents a set of one or more post processes in Babylon.
  75881. * A post process can be used to apply a shader to a texture after it is rendered.
  75882. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  75883. */
  75884. var PostProcessRenderEffect = /** @class */ (function () {
  75885. /**
  75886. * Instantiates a post process render effect.
  75887. * A post process can be used to apply a shader to a texture after it is rendered.
  75888. * @param engine The engine the effect is tied to
  75889. * @param name The name of the effect
  75890. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  75891. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  75892. */
  75893. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  75894. this._name = name;
  75895. this._singleInstance = singleInstance || true;
  75896. this._getPostProcesses = getPostProcesses;
  75897. this._cameras = {};
  75898. this._indicesForCamera = {};
  75899. this._postProcesses = {};
  75900. }
  75901. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  75902. /**
  75903. * Checks if all the post processes in the effect are supported.
  75904. */
  75905. get: function () {
  75906. for (var index in this._postProcesses) {
  75907. if (this._postProcesses.hasOwnProperty(index)) {
  75908. var pps = this._postProcesses[index];
  75909. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  75910. if (!pps[ppIndex].isSupported) {
  75911. return false;
  75912. }
  75913. }
  75914. }
  75915. }
  75916. return true;
  75917. },
  75918. enumerable: true,
  75919. configurable: true
  75920. });
  75921. /**
  75922. * Updates the current state of the effect
  75923. * @hidden
  75924. */
  75925. PostProcessRenderEffect.prototype._update = function () {
  75926. };
  75927. /**
  75928. * Attaches the effect on cameras
  75929. * @param cameras The camera to attach to.
  75930. * @hidden
  75931. */
  75932. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  75933. var _this = this;
  75934. var cameraKey;
  75935. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75936. if (!cams) {
  75937. return;
  75938. }
  75939. for (var i = 0; i < cams.length; i++) {
  75940. var camera = cams[i];
  75941. var cameraName = camera.name;
  75942. if (this._singleInstance) {
  75943. cameraKey = 0;
  75944. }
  75945. else {
  75946. cameraKey = cameraName;
  75947. }
  75948. if (!this._postProcesses[cameraKey]) {
  75949. var postProcess = this._getPostProcesses();
  75950. if (postProcess) {
  75951. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  75952. }
  75953. }
  75954. if (!this._indicesForCamera[cameraName]) {
  75955. this._indicesForCamera[cameraName] = [];
  75956. }
  75957. this._postProcesses[cameraKey].forEach(function (postProcess) {
  75958. var index = camera.attachPostProcess(postProcess);
  75959. _this._indicesForCamera[cameraName].push(index);
  75960. });
  75961. if (!this._cameras[cameraName]) {
  75962. this._cameras[cameraName] = camera;
  75963. }
  75964. }
  75965. };
  75966. /**
  75967. * Detatches the effect on cameras
  75968. * @param cameras The camera to detatch from.
  75969. * @hidden
  75970. */
  75971. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  75972. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75973. if (!cams) {
  75974. return;
  75975. }
  75976. for (var i = 0; i < cams.length; i++) {
  75977. var camera = cams[i];
  75978. var cameraName = camera.name;
  75979. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75980. camera.detachPostProcess(postProcess);
  75981. });
  75982. if (this._cameras[cameraName]) {
  75983. //this._indicesForCamera.splice(index, 1);
  75984. this._cameras[cameraName] = null;
  75985. }
  75986. }
  75987. };
  75988. /**
  75989. * Enables the effect on given cameras
  75990. * @param cameras The camera to enable.
  75991. * @hidden
  75992. */
  75993. PostProcessRenderEffect.prototype._enable = function (cameras) {
  75994. var _this = this;
  75995. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75996. if (!cams) {
  75997. return;
  75998. }
  75999. for (var i = 0; i < cams.length; i++) {
  76000. var camera = cams[i];
  76001. var cameraName = camera.name;
  76002. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76003. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76004. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76005. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76006. });
  76007. }
  76008. }
  76009. }
  76010. };
  76011. /**
  76012. * Disables the effect on the given cameras
  76013. * @param cameras The camera to disable.
  76014. * @hidden
  76015. */
  76016. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76017. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76018. if (!cams) {
  76019. return;
  76020. }
  76021. for (var i = 0; i < cams.length; i++) {
  76022. var camera = cams[i];
  76023. var cameraName = camera.name;
  76024. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76025. camera.detachPostProcess(postProcess);
  76026. });
  76027. }
  76028. };
  76029. /**
  76030. * Gets a list of the post processes contained in the effect.
  76031. * @param camera The camera to get the post processes on.
  76032. * @returns The list of the post processes in the effect.
  76033. */
  76034. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76035. if (this._singleInstance) {
  76036. return this._postProcesses[0];
  76037. }
  76038. else {
  76039. if (!camera) {
  76040. return null;
  76041. }
  76042. return this._postProcesses[camera.name];
  76043. }
  76044. };
  76045. return PostProcessRenderEffect;
  76046. }());
  76047. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76048. })(BABYLON || (BABYLON = {}));
  76049. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76050. var BABYLON;
  76051. (function (BABYLON) {
  76052. var PostProcessRenderPipeline = /** @class */ (function () {
  76053. function PostProcessRenderPipeline(engine, name) {
  76054. this.engine = engine;
  76055. this._name = name;
  76056. this._renderEffects = {};
  76057. this._renderEffectsForIsolatedPass = new Array();
  76058. this._cameras = [];
  76059. }
  76060. PostProcessRenderPipeline.prototype.getClassName = function () {
  76061. return "PostProcessRenderPipeline";
  76062. };
  76063. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76064. get: function () {
  76065. for (var renderEffectName in this._renderEffects) {
  76066. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76067. if (!this._renderEffects[renderEffectName].isSupported) {
  76068. return false;
  76069. }
  76070. }
  76071. }
  76072. return true;
  76073. },
  76074. enumerable: true,
  76075. configurable: true
  76076. });
  76077. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76078. this._renderEffects[renderEffect._name] = renderEffect;
  76079. };
  76080. // private
  76081. /** @hidden */
  76082. PostProcessRenderPipeline.prototype._rebuild = function () {
  76083. };
  76084. /** @hidden */
  76085. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76086. var renderEffects = this._renderEffects[renderEffectName];
  76087. if (!renderEffects) {
  76088. return;
  76089. }
  76090. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76091. };
  76092. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76093. var renderEffects = this._renderEffects[renderEffectName];
  76094. if (!renderEffects) {
  76095. return;
  76096. }
  76097. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76098. };
  76099. /** @hidden */
  76100. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76101. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76102. if (!cams) {
  76103. return;
  76104. }
  76105. var indicesToDelete = [];
  76106. var i;
  76107. for (i = 0; i < cams.length; i++) {
  76108. var camera = cams[i];
  76109. var cameraName = camera.name;
  76110. if (this._cameras.indexOf(camera) === -1) {
  76111. this._cameras[cameraName] = camera;
  76112. }
  76113. else if (unique) {
  76114. indicesToDelete.push(i);
  76115. }
  76116. }
  76117. for (i = 0; i < indicesToDelete.length; i++) {
  76118. cameras.splice(indicesToDelete[i], 1);
  76119. }
  76120. for (var renderEffectName in this._renderEffects) {
  76121. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76122. this._renderEffects[renderEffectName]._attachCameras(cams);
  76123. }
  76124. }
  76125. };
  76126. /** @hidden */
  76127. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76128. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76129. if (!cams) {
  76130. return;
  76131. }
  76132. for (var renderEffectName in this._renderEffects) {
  76133. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76134. this._renderEffects[renderEffectName]._detachCameras(cams);
  76135. }
  76136. }
  76137. for (var i = 0; i < cams.length; i++) {
  76138. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76139. }
  76140. };
  76141. /** @hidden */
  76142. PostProcessRenderPipeline.prototype._update = function () {
  76143. for (var renderEffectName in this._renderEffects) {
  76144. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76145. this._renderEffects[renderEffectName]._update();
  76146. }
  76147. }
  76148. for (var i = 0; i < this._cameras.length; i++) {
  76149. var cameraName = this._cameras[i].name;
  76150. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76151. this._renderEffectsForIsolatedPass[cameraName]._update();
  76152. }
  76153. }
  76154. };
  76155. /** @hidden */
  76156. PostProcessRenderPipeline.prototype._reset = function () {
  76157. this._renderEffects = {};
  76158. this._renderEffectsForIsolatedPass = new Array();
  76159. };
  76160. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76161. // 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)
  76162. var effectKeys = Object.keys(this._renderEffects);
  76163. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76164. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76165. if (postProcesses) {
  76166. postProcesses[0].samples = sampleCount;
  76167. return true;
  76168. }
  76169. }
  76170. return false;
  76171. };
  76172. PostProcessRenderPipeline.prototype.dispose = function () {
  76173. // Must be implemented by children
  76174. };
  76175. __decorate([
  76176. BABYLON.serialize()
  76177. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76178. return PostProcessRenderPipeline;
  76179. }());
  76180. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76181. })(BABYLON || (BABYLON = {}));
  76182. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76183. var BABYLON;
  76184. (function (BABYLON) {
  76185. /**
  76186. * This represents a depth renderer in Babylon.
  76187. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76188. */
  76189. var DepthRenderer = /** @class */ (function () {
  76190. /**
  76191. * Instantiates a depth renderer
  76192. * @param scene The scene the renderer belongs to
  76193. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76194. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76195. */
  76196. function DepthRenderer(scene, type, camera) {
  76197. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76198. if (camera === void 0) { camera = null; }
  76199. var _this = this;
  76200. this._scene = scene;
  76201. // Register the G Buffer component to the scene.
  76202. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  76203. if (!component) {
  76204. component = new BABYLON.DepthRendererSceneComponent(scene);
  76205. scene._addComponent(component);
  76206. }
  76207. this._camera = camera;
  76208. var engine = scene.getEngine();
  76209. // Render target
  76210. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76211. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76212. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76213. this._depthMap.refreshRate = 1;
  76214. this._depthMap.renderParticles = false;
  76215. this._depthMap.renderList = null;
  76216. // Camera to get depth map from to support multiple concurrent cameras
  76217. this._depthMap.activeCamera = this._camera;
  76218. this._depthMap.ignoreCameraViewport = true;
  76219. this._depthMap.useCameraPostProcesses = false;
  76220. // set default depth value to 1.0 (far away)
  76221. this._depthMap.onClearObservable.add(function (engine) {
  76222. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76223. });
  76224. // Custom render function
  76225. var renderSubMesh = function (subMesh) {
  76226. var mesh = subMesh.getRenderingMesh();
  76227. var scene = _this._scene;
  76228. var engine = scene.getEngine();
  76229. var material = subMesh.getMaterial();
  76230. if (!material) {
  76231. return;
  76232. }
  76233. // Culling and reverse (right handed system)
  76234. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76235. // Managing instances
  76236. var batch = mesh._getInstancesRenderList(subMesh._id);
  76237. if (batch.mustReturn) {
  76238. return;
  76239. }
  76240. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76241. var camera = _this._camera || scene.activeCamera;
  76242. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76243. engine.enableEffect(_this._effect);
  76244. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76245. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76246. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76247. // Alpha test
  76248. if (material && material.needAlphaTesting()) {
  76249. var alphaTexture = material.getAlphaTestTexture();
  76250. if (alphaTexture) {
  76251. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76252. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76253. }
  76254. }
  76255. // Bones
  76256. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76257. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76258. }
  76259. // Draw
  76260. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76261. }
  76262. };
  76263. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76264. var index;
  76265. if (depthOnlySubMeshes.length) {
  76266. engine.setColorWrite(false);
  76267. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76268. renderSubMesh(depthOnlySubMeshes.data[index]);
  76269. }
  76270. engine.setColorWrite(true);
  76271. }
  76272. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76273. renderSubMesh(opaqueSubMeshes.data[index]);
  76274. }
  76275. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76276. renderSubMesh(alphaTestSubMeshes.data[index]);
  76277. }
  76278. };
  76279. }
  76280. /**
  76281. * Creates the depth rendering effect and checks if the effect is ready.
  76282. * @param subMesh The submesh to be used to render the depth map of
  76283. * @param useInstances If multiple world instances should be used
  76284. * @returns if the depth renderer is ready to render the depth map
  76285. */
  76286. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76287. var material = subMesh.getMaterial();
  76288. if (material.disableDepthWrite) {
  76289. return false;
  76290. }
  76291. var defines = [];
  76292. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76293. var mesh = subMesh.getMesh();
  76294. // Alpha test
  76295. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76296. defines.push("#define ALPHATEST");
  76297. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76298. attribs.push(BABYLON.VertexBuffer.UVKind);
  76299. defines.push("#define UV1");
  76300. }
  76301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76302. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76303. defines.push("#define UV2");
  76304. }
  76305. }
  76306. // Bones
  76307. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76310. if (mesh.numBoneInfluencers > 4) {
  76311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76313. }
  76314. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76315. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76316. }
  76317. else {
  76318. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76319. }
  76320. // Instances
  76321. if (useInstances) {
  76322. defines.push("#define INSTANCES");
  76323. attribs.push("world0");
  76324. attribs.push("world1");
  76325. attribs.push("world2");
  76326. attribs.push("world3");
  76327. }
  76328. // Get correct effect
  76329. var join = defines.join("\n");
  76330. if (this._cachedDefines !== join) {
  76331. this._cachedDefines = join;
  76332. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76333. }
  76334. return this._effect.isReady();
  76335. };
  76336. /**
  76337. * Gets the texture which the depth map will be written to.
  76338. * @returns The depth map texture
  76339. */
  76340. DepthRenderer.prototype.getDepthMap = function () {
  76341. return this._depthMap;
  76342. };
  76343. /**
  76344. * Disposes of the depth renderer.
  76345. */
  76346. DepthRenderer.prototype.dispose = function () {
  76347. this._depthMap.dispose();
  76348. };
  76349. return DepthRenderer;
  76350. }());
  76351. BABYLON.DepthRenderer = DepthRenderer;
  76352. })(BABYLON || (BABYLON = {}));
  76353. //# sourceMappingURL=babylon.depthRenderer.js.map
  76354. var BABYLON;
  76355. (function (BABYLON) {
  76356. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  76357. camera = camera || this.activeCamera;
  76358. if (!camera) {
  76359. throw "No camera available to enable depth renderer";
  76360. }
  76361. if (!this._depthRenderer) {
  76362. this._depthRenderer = {};
  76363. }
  76364. if (!this._depthRenderer[camera.id]) {
  76365. var textureType = 0;
  76366. if (this.getEngine().getCaps().textureHalfFloatRender) {
  76367. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76368. }
  76369. else if (this.getEngine().getCaps().textureFloatRender) {
  76370. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76371. }
  76372. else {
  76373. throw "Depth renderer does not support int texture type";
  76374. }
  76375. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  76376. }
  76377. return this._depthRenderer[camera.id];
  76378. };
  76379. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  76380. camera = camera || this.activeCamera;
  76381. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  76382. return;
  76383. }
  76384. this._depthRenderer[camera.id].dispose();
  76385. delete this._depthRenderer[camera.id];
  76386. };
  76387. /**
  76388. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  76389. * in several rendering techniques.
  76390. */
  76391. var DepthRendererSceneComponent = /** @class */ (function () {
  76392. /**
  76393. * Creates a new instance of the component for the given scene
  76394. * @param scene Defines the scene to register the component in
  76395. */
  76396. function DepthRendererSceneComponent(scene) {
  76397. /**
  76398. * The component name helpfull to identify the component in the list of scene components.
  76399. */
  76400. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  76401. this.scene = scene;
  76402. }
  76403. /**
  76404. * Registers the component in a given scene
  76405. */
  76406. DepthRendererSceneComponent.prototype.register = function () {
  76407. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  76408. };
  76409. /**
  76410. * Rebuilds the elements related to this component in case of
  76411. * context lost for instance.
  76412. */
  76413. DepthRendererSceneComponent.prototype.rebuild = function () {
  76414. // Nothing to do for this component
  76415. };
  76416. /**
  76417. * Disposes the component and the associated ressources
  76418. */
  76419. DepthRendererSceneComponent.prototype.dispose = function () {
  76420. for (var key in this.scene._depthRenderer) {
  76421. this.scene._depthRenderer[key].dispose();
  76422. }
  76423. };
  76424. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76425. if (this.scene._depthRenderer) {
  76426. for (var key in this.scene._depthRenderer) {
  76427. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  76428. }
  76429. }
  76430. };
  76431. return DepthRendererSceneComponent;
  76432. }());
  76433. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  76434. })(BABYLON || (BABYLON = {}));
  76435. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  76436. var BABYLON;
  76437. (function (BABYLON) {
  76438. /**
  76439. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76440. */
  76441. var GeometryBufferRenderer = /** @class */ (function () {
  76442. /**
  76443. * Creates a new G Buffer for the scene
  76444. * @param scene The scene the buffer belongs to
  76445. * @param ratio How big is the buffer related to the main canvas.
  76446. */
  76447. function GeometryBufferRenderer(scene, ratio) {
  76448. if (ratio === void 0) { ratio = 1; }
  76449. this._enablePosition = false;
  76450. this._scene = scene;
  76451. this._ratio = ratio;
  76452. // Register the G Buffer component to the scene.
  76453. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  76454. if (!component) {
  76455. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  76456. scene._addComponent(component);
  76457. }
  76458. // Render target
  76459. this._createRenderTargets();
  76460. }
  76461. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76462. /**
  76463. * Set the render list (meshes to be rendered) used in the G buffer.
  76464. */
  76465. set: function (meshes) {
  76466. this._multiRenderTarget.renderList = meshes;
  76467. },
  76468. enumerable: true,
  76469. configurable: true
  76470. });
  76471. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76472. /**
  76473. * Gets wether or not G buffer are supported by the running hardware.
  76474. * This requires draw buffer supports
  76475. */
  76476. get: function () {
  76477. return this._multiRenderTarget.isSupported;
  76478. },
  76479. enumerable: true,
  76480. configurable: true
  76481. });
  76482. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76483. /**
  76484. * Gets wether or not position are enabled for the G buffer.
  76485. */
  76486. get: function () {
  76487. return this._enablePosition;
  76488. },
  76489. /**
  76490. * Sets wether or not position are enabled for the G buffer.
  76491. */
  76492. set: function (enable) {
  76493. this._enablePosition = enable;
  76494. this.dispose();
  76495. this._createRenderTargets();
  76496. },
  76497. enumerable: true,
  76498. configurable: true
  76499. });
  76500. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76501. /**
  76502. * Gets the scene associated with the buffer.
  76503. */
  76504. get: function () {
  76505. return this._scene;
  76506. },
  76507. enumerable: true,
  76508. configurable: true
  76509. });
  76510. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76511. /**
  76512. * Gets the ratio used by the buffer during its creation.
  76513. * How big is the buffer related to the main canvas.
  76514. */
  76515. get: function () {
  76516. return this._ratio;
  76517. },
  76518. enumerable: true,
  76519. configurable: true
  76520. });
  76521. /**
  76522. * Checks wether everything is ready to render a submesh to the G buffer.
  76523. * @param subMesh the submesh to check readiness for
  76524. * @param useInstances is the mesh drawn using instance or not
  76525. * @returns true if ready otherwise false
  76526. */
  76527. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76528. var material = subMesh.getMaterial();
  76529. if (material && material.disableDepthWrite) {
  76530. return false;
  76531. }
  76532. var defines = [];
  76533. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76534. var mesh = subMesh.getMesh();
  76535. // Alpha test
  76536. if (material && material.needAlphaTesting()) {
  76537. defines.push("#define ALPHATEST");
  76538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76539. attribs.push(BABYLON.VertexBuffer.UVKind);
  76540. defines.push("#define UV1");
  76541. }
  76542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76543. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76544. defines.push("#define UV2");
  76545. }
  76546. }
  76547. // Buffers
  76548. if (this._enablePosition) {
  76549. defines.push("#define POSITION");
  76550. }
  76551. // Bones
  76552. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76555. if (mesh.numBoneInfluencers > 4) {
  76556. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76557. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76558. }
  76559. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76560. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76561. }
  76562. else {
  76563. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76564. }
  76565. // Instances
  76566. if (useInstances) {
  76567. defines.push("#define INSTANCES");
  76568. attribs.push("world0");
  76569. attribs.push("world1");
  76570. attribs.push("world2");
  76571. attribs.push("world3");
  76572. }
  76573. // Get correct effect
  76574. var join = defines.join("\n");
  76575. if (this._cachedDefines !== join) {
  76576. this._cachedDefines = join;
  76577. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76578. }
  76579. return this._effect.isReady();
  76580. };
  76581. /**
  76582. * Gets the current underlying G Buffer.
  76583. * @returns the buffer
  76584. */
  76585. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76586. return this._multiRenderTarget;
  76587. };
  76588. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76589. /**
  76590. * Gets the number of samples used to render the buffer (anti aliasing).
  76591. */
  76592. get: function () {
  76593. return this._multiRenderTarget.samples;
  76594. },
  76595. /**
  76596. * Sets the number of samples used to render the buffer (anti aliasing).
  76597. */
  76598. set: function (value) {
  76599. this._multiRenderTarget.samples = value;
  76600. },
  76601. enumerable: true,
  76602. configurable: true
  76603. });
  76604. /**
  76605. * Disposes the renderer and frees up associated resources.
  76606. */
  76607. GeometryBufferRenderer.prototype.dispose = function () {
  76608. this.getGBuffer().dispose();
  76609. };
  76610. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76611. var _this = this;
  76612. var engine = this._scene.getEngine();
  76613. var count = this._enablePosition ? 3 : 2;
  76614. 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 });
  76615. if (!this.isSupported) {
  76616. return;
  76617. }
  76618. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76619. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76620. this._multiRenderTarget.refreshRate = 1;
  76621. this._multiRenderTarget.renderParticles = false;
  76622. this._multiRenderTarget.renderList = null;
  76623. // set default depth value to 1.0 (far away)
  76624. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76625. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76626. });
  76627. // Custom render function
  76628. var renderSubMesh = function (subMesh) {
  76629. var mesh = subMesh.getRenderingMesh();
  76630. var scene = _this._scene;
  76631. var engine = scene.getEngine();
  76632. var material = subMesh.getMaterial();
  76633. if (!material) {
  76634. return;
  76635. }
  76636. // Culling
  76637. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76638. // Managing instances
  76639. var batch = mesh._getInstancesRenderList(subMesh._id);
  76640. if (batch.mustReturn) {
  76641. return;
  76642. }
  76643. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76644. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76645. engine.enableEffect(_this._effect);
  76646. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76647. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76648. _this._effect.setMatrix("view", scene.getViewMatrix());
  76649. // Alpha test
  76650. if (material && material.needAlphaTesting()) {
  76651. var alphaTexture = material.getAlphaTestTexture();
  76652. if (alphaTexture) {
  76653. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76654. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76655. }
  76656. }
  76657. // Bones
  76658. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76659. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76660. }
  76661. // Draw
  76662. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76663. }
  76664. };
  76665. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76666. var index;
  76667. if (depthOnlySubMeshes.length) {
  76668. engine.setColorWrite(false);
  76669. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76670. renderSubMesh(depthOnlySubMeshes.data[index]);
  76671. }
  76672. engine.setColorWrite(true);
  76673. }
  76674. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76675. renderSubMesh(opaqueSubMeshes.data[index]);
  76676. }
  76677. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76678. renderSubMesh(alphaTestSubMeshes.data[index]);
  76679. }
  76680. };
  76681. };
  76682. return GeometryBufferRenderer;
  76683. }());
  76684. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76685. })(BABYLON || (BABYLON = {}));
  76686. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76687. var BABYLON;
  76688. (function (BABYLON) {
  76689. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  76690. get: function () {
  76691. this._geometryBufferRenderer;
  76692. },
  76693. set: function (value) {
  76694. if (value && value.isSupported) {
  76695. this._geometryBufferRenderer = value;
  76696. }
  76697. ;
  76698. },
  76699. enumerable: true,
  76700. configurable: true
  76701. });
  76702. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  76703. if (ratio === void 0) { ratio = 1; }
  76704. if (this._geometryBufferRenderer) {
  76705. return this._geometryBufferRenderer;
  76706. }
  76707. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  76708. if (!this._geometryBufferRenderer.isSupported) {
  76709. this._geometryBufferRenderer = null;
  76710. }
  76711. return this._geometryBufferRenderer;
  76712. };
  76713. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  76714. if (!this._geometryBufferRenderer) {
  76715. return;
  76716. }
  76717. this._geometryBufferRenderer.dispose();
  76718. this._geometryBufferRenderer = null;
  76719. };
  76720. /**
  76721. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  76722. * in several rendering techniques.
  76723. */
  76724. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  76725. /**
  76726. * Creates a new instance of the component for the given scene
  76727. * @param scene Defines the scene to register the component in
  76728. */
  76729. function GeometryBufferRendererSceneComponent(scene) {
  76730. /**
  76731. * The component name helpfull to identify the component in the list of scene components.
  76732. */
  76733. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  76734. this.scene = scene;
  76735. }
  76736. /**
  76737. * Registers the component in a given scene
  76738. */
  76739. GeometryBufferRendererSceneComponent.prototype.register = function () {
  76740. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  76741. };
  76742. /**
  76743. * Rebuilds the elements related to this component in case of
  76744. * context lost for instance.
  76745. */
  76746. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  76747. // Nothing to do for this component
  76748. };
  76749. /**
  76750. * Disposes the component and the associated ressources
  76751. */
  76752. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  76753. // Nothing to do for this component
  76754. };
  76755. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76756. if (this.scene._geometryBufferRenderer) {
  76757. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  76758. }
  76759. };
  76760. return GeometryBufferRendererSceneComponent;
  76761. }());
  76762. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  76763. })(BABYLON || (BABYLON = {}));
  76764. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  76765. var BABYLON;
  76766. (function (BABYLON) {
  76767. var SSAORenderingPipeline = /** @class */ (function (_super) {
  76768. __extends(SSAORenderingPipeline, _super);
  76769. /**
  76770. * @constructor
  76771. * @param {string} name - The rendering pipeline name
  76772. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76773. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  76774. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76775. */
  76776. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  76777. var _this = _super.call(this, scene.getEngine(), name) || this;
  76778. // Members
  76779. /**
  76780. * The PassPostProcess id in the pipeline that contains the original scene color
  76781. */
  76782. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  76783. /**
  76784. * The SSAO PostProcess id in the pipeline
  76785. */
  76786. _this.SSAORenderEffect = "SSAORenderEffect";
  76787. /**
  76788. * The horizontal blur PostProcess id in the pipeline
  76789. */
  76790. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  76791. /**
  76792. * The vertical blur PostProcess id in the pipeline
  76793. */
  76794. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  76795. /**
  76796. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  76797. */
  76798. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  76799. /**
  76800. * The output strength of the SSAO post-process. Default value is 1.0.
  76801. */
  76802. _this.totalStrength = 1.0;
  76803. /**
  76804. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  76805. */
  76806. _this.radius = 0.0001;
  76807. /**
  76808. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  76809. * Must not be equal to fallOff and superior to fallOff.
  76810. * Default value is 0.975
  76811. */
  76812. _this.area = 0.0075;
  76813. /**
  76814. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  76815. * Must not be equal to area and inferior to area.
  76816. * Default value is 0.0
  76817. */
  76818. _this.fallOff = 0.000001;
  76819. /**
  76820. * The base color of the SSAO post-process
  76821. * The final result is "base + ssao" between [0, 1]
  76822. */
  76823. _this.base = 0.5;
  76824. _this._firstUpdate = true;
  76825. _this._scene = scene;
  76826. // Set up assets
  76827. _this._createRandomTexture();
  76828. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76829. var ssaoRatio = ratio.ssaoRatio || ratio;
  76830. var combineRatio = ratio.combineRatio || ratio;
  76831. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  76832. _this._createSSAOPostProcess(ssaoRatio);
  76833. _this._createBlurPostProcess(ssaoRatio);
  76834. _this._createSSAOCombinePostProcess(combineRatio);
  76835. // Set up pipeline
  76836. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  76837. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  76838. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  76839. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  76840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  76841. // Finish
  76842. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76843. if (cameras)
  76844. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76845. return _this;
  76846. }
  76847. // Public Methods
  76848. /**
  76849. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  76850. */
  76851. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76852. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76853. for (var i = 0; i < this._scene.cameras.length; i++) {
  76854. var camera = this._scene.cameras[i];
  76855. this._originalColorPostProcess.dispose(camera);
  76856. this._ssaoPostProcess.dispose(camera);
  76857. this._blurHPostProcess.dispose(camera);
  76858. this._blurVPostProcess.dispose(camera);
  76859. this._ssaoCombinePostProcess.dispose(camera);
  76860. }
  76861. this._randomTexture.dispose();
  76862. if (disableDepthRender)
  76863. this._scene.disableDepthRenderer();
  76864. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76865. _super.prototype.dispose.call(this);
  76866. };
  76867. // Private Methods
  76868. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  76869. var _this = this;
  76870. var size = 16;
  76871. 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);
  76872. 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);
  76873. this._blurHPostProcess.onActivateObservable.add(function () {
  76874. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  76875. _this._blurHPostProcess.kernel = size * dw;
  76876. });
  76877. this._blurVPostProcess.onActivateObservable.add(function () {
  76878. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  76879. _this._blurVPostProcess.kernel = size * dw;
  76880. });
  76881. };
  76882. /** @hidden */
  76883. SSAORenderingPipeline.prototype._rebuild = function () {
  76884. this._firstUpdate = true;
  76885. _super.prototype._rebuild.call(this);
  76886. };
  76887. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76888. var _this = this;
  76889. var numSamples = 16;
  76890. var sampleSphere = [
  76891. 0.5381, 0.1856, -0.4319,
  76892. 0.1379, 0.2486, 0.4430,
  76893. 0.3371, 0.5679, -0.0057,
  76894. -0.6999, -0.0451, -0.0019,
  76895. 0.0689, -0.1598, -0.8547,
  76896. 0.0560, 0.0069, -0.1843,
  76897. -0.0146, 0.1402, 0.0762,
  76898. 0.0100, -0.1924, -0.0344,
  76899. -0.3577, -0.5301, -0.4358,
  76900. -0.3169, 0.1063, 0.0158,
  76901. 0.0103, -0.5869, 0.0046,
  76902. -0.0897, -0.4940, 0.3287,
  76903. 0.7119, -0.0154, -0.0918,
  76904. -0.0533, 0.0596, -0.5411,
  76905. 0.0352, -0.0631, 0.5460,
  76906. -0.4776, 0.2847, -0.0271
  76907. ];
  76908. var samplesFactor = 1.0 / numSamples;
  76909. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  76910. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76911. "area", "fallOff", "base", "range", "viewport"
  76912. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76913. this._ssaoPostProcess.onApply = function (effect) {
  76914. if (_this._firstUpdate) {
  76915. effect.setArray3("sampleSphere", sampleSphere);
  76916. effect.setFloat("samplesFactor", samplesFactor);
  76917. effect.setFloat("randTextureTiles", 4.0);
  76918. }
  76919. effect.setFloat("totalStrength", _this.totalStrength);
  76920. effect.setFloat("radius", _this.radius);
  76921. effect.setFloat("area", _this.area);
  76922. effect.setFloat("fallOff", _this.fallOff);
  76923. effect.setFloat("base", _this.base);
  76924. effect.setTexture("textureSampler", _this._depthTexture);
  76925. effect.setTexture("randomSampler", _this._randomTexture);
  76926. };
  76927. };
  76928. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76929. var _this = this;
  76930. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76931. this._ssaoCombinePostProcess.onApply = function (effect) {
  76932. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  76933. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76934. };
  76935. };
  76936. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  76937. var size = 512;
  76938. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76939. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76940. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76941. var context = this._randomTexture.getContext();
  76942. var rand = function (min, max) {
  76943. return Math.random() * (max - min) + min;
  76944. };
  76945. var randVector = BABYLON.Vector3.Zero();
  76946. for (var x = 0; x < size; x++) {
  76947. for (var y = 0; y < size; y++) {
  76948. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  76949. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  76950. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  76951. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76952. context.fillRect(x, y, 1, 1);
  76953. }
  76954. }
  76955. this._randomTexture.update(false);
  76956. };
  76957. __decorate([
  76958. BABYLON.serialize()
  76959. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  76960. __decorate([
  76961. BABYLON.serialize()
  76962. ], SSAORenderingPipeline.prototype, "radius", void 0);
  76963. __decorate([
  76964. BABYLON.serialize()
  76965. ], SSAORenderingPipeline.prototype, "area", void 0);
  76966. __decorate([
  76967. BABYLON.serialize()
  76968. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  76969. __decorate([
  76970. BABYLON.serialize()
  76971. ], SSAORenderingPipeline.prototype, "base", void 0);
  76972. return SSAORenderingPipeline;
  76973. }(BABYLON.PostProcessRenderPipeline));
  76974. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  76975. })(BABYLON || (BABYLON = {}));
  76976. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  76977. var BABYLON;
  76978. (function (BABYLON) {
  76979. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  76980. __extends(SSAO2RenderingPipeline, _super);
  76981. /**
  76982. * @constructor
  76983. * @param {string} name - The rendering pipeline name
  76984. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76985. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  76986. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76987. */
  76988. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  76989. var _this = _super.call(this, scene.getEngine(), name) || this;
  76990. // Members
  76991. /**
  76992. * The PassPostProcess id in the pipeline that contains the original scene color
  76993. */
  76994. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  76995. /**
  76996. * The SSAO PostProcess id in the pipeline
  76997. */
  76998. _this.SSAORenderEffect = "SSAORenderEffect";
  76999. /**
  77000. * The horizontal blur PostProcess id in the pipeline
  77001. */
  77002. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77003. /**
  77004. * The vertical blur PostProcess id in the pipeline
  77005. */
  77006. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77007. /**
  77008. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77009. */
  77010. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77011. /**
  77012. * The output strength of the SSAO post-process. Default value is 1.0.
  77013. */
  77014. _this.totalStrength = 1.0;
  77015. /**
  77016. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77017. */
  77018. _this.maxZ = 100.0;
  77019. /**
  77020. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77021. */
  77022. _this.minZAspect = 0.2;
  77023. _this._samples = 8;
  77024. _this._textureSamples = 1;
  77025. /**
  77026. * Are we using bilateral blur ?
  77027. */
  77028. _this._expensiveBlur = true;
  77029. /**
  77030. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77031. */
  77032. _this.radius = 2.0;
  77033. /**
  77034. * The base color of the SSAO post-process
  77035. * The final result is "base + ssao" between [0, 1]
  77036. */
  77037. _this.base = 0;
  77038. _this._firstUpdate = true;
  77039. _this._bits = new Uint32Array(1);
  77040. _this._scene = scene;
  77041. _this._ratio = ratio;
  77042. if (!_this.isSupported) {
  77043. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77044. return _this;
  77045. }
  77046. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77047. var blurRatio = _this._ratio.blurRatio || ratio;
  77048. // Set up assets
  77049. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77050. _this._createRandomTexture();
  77051. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77052. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77053. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77054. _this._originalColorPostProcess.samples = _this.textureSamples;
  77055. _this._createSSAOPostProcess(1.0);
  77056. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77057. _this._createSSAOCombinePostProcess(blurRatio);
  77058. // Set up pipeline
  77059. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77064. // Finish
  77065. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77066. if (cameras)
  77067. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77068. return _this;
  77069. }
  77070. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77071. get: function () {
  77072. return this._samples;
  77073. },
  77074. /**
  77075. * Number of samples used for the SSAO calculations. Default value is 8
  77076. */
  77077. set: function (n) {
  77078. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77079. this._samples = n;
  77080. this._sampleSphere = this._generateHemisphere();
  77081. this._firstUpdate = true;
  77082. },
  77083. enumerable: true,
  77084. configurable: true
  77085. });
  77086. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  77087. get: function () {
  77088. return this._textureSamples;
  77089. },
  77090. /**
  77091. * Number of samples to use for antialiasing
  77092. */
  77093. set: function (n) {
  77094. this._textureSamples = n;
  77095. this._originalColorPostProcess.samples = n;
  77096. this._blurHPostProcess.samples = n;
  77097. this._blurVPostProcess.samples = n;
  77098. this._ssaoPostProcess.samples = n;
  77099. this._ssaoCombinePostProcess.samples = n;
  77100. },
  77101. enumerable: true,
  77102. configurable: true
  77103. });
  77104. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  77105. get: function () {
  77106. return this._expensiveBlur;
  77107. },
  77108. set: function (b) {
  77109. 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"]);
  77110. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  77111. this._expensiveBlur = b;
  77112. this._firstUpdate = true;
  77113. },
  77114. enumerable: true,
  77115. configurable: true
  77116. });
  77117. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  77118. /**
  77119. * Support test.
  77120. */
  77121. get: function () {
  77122. var engine = BABYLON.Engine.LastCreatedEngine;
  77123. if (!engine) {
  77124. return false;
  77125. }
  77126. return engine.getCaps().drawBuffersExtension;
  77127. },
  77128. enumerable: true,
  77129. configurable: true
  77130. });
  77131. // Public Methods
  77132. /**
  77133. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77134. */
  77135. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  77136. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  77137. for (var i = 0; i < this._scene.cameras.length; i++) {
  77138. var camera = this._scene.cameras[i];
  77139. this._originalColorPostProcess.dispose(camera);
  77140. this._ssaoPostProcess.dispose(camera);
  77141. this._blurHPostProcess.dispose(camera);
  77142. this._blurVPostProcess.dispose(camera);
  77143. this._ssaoCombinePostProcess.dispose(camera);
  77144. }
  77145. this._randomTexture.dispose();
  77146. if (disableGeometryBufferRenderer)
  77147. this._scene.disableGeometryBufferRenderer();
  77148. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77149. _super.prototype.dispose.call(this);
  77150. };
  77151. // Private Methods
  77152. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  77153. var _this = this;
  77154. this._samplerOffsets = [];
  77155. var expensive = this.expensiveBlur;
  77156. for (var i = -8; i < 8; i++) {
  77157. this._samplerOffsets.push(i * 2 + 0.5);
  77158. }
  77159. 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");
  77160. this._blurHPostProcess.onApply = function (effect) {
  77161. if (!_this._scene.activeCamera) {
  77162. return;
  77163. }
  77164. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  77165. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77166. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77167. effect.setFloat("radius", _this.radius);
  77168. effect.setTexture("depthSampler", _this._depthTexture);
  77169. if (_this._firstUpdate) {
  77170. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77171. }
  77172. };
  77173. 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");
  77174. this._blurVPostProcess.onApply = function (effect) {
  77175. if (!_this._scene.activeCamera) {
  77176. return;
  77177. }
  77178. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  77179. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77180. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77181. effect.setFloat("radius", _this.radius);
  77182. effect.setTexture("depthSampler", _this._depthTexture);
  77183. if (_this._firstUpdate) {
  77184. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77185. _this._firstUpdate = false;
  77186. }
  77187. };
  77188. this._blurHPostProcess.samples = this.textureSamples;
  77189. this._blurVPostProcess.samples = this.textureSamples;
  77190. };
  77191. /** @hidden */
  77192. SSAO2RenderingPipeline.prototype._rebuild = function () {
  77193. this._firstUpdate = true;
  77194. _super.prototype._rebuild.call(this);
  77195. };
  77196. //Van der Corput radical inverse
  77197. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  77198. this._bits[0] = i;
  77199. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  77200. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  77201. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  77202. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  77203. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  77204. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  77205. };
  77206. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  77207. return [i / n, this._radicalInverse_VdC(i)];
  77208. };
  77209. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  77210. var phi = v * 2.0 * Math.PI;
  77211. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  77212. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  77213. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  77214. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  77215. };
  77216. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  77217. var numSamples = this.samples;
  77218. var result = [];
  77219. var vector;
  77220. var i = 0;
  77221. while (i < numSamples) {
  77222. if (numSamples < 16) {
  77223. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  77224. }
  77225. else {
  77226. var rand = this._hammersley(i, numSamples);
  77227. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  77228. }
  77229. result.push(vector.x, vector.y, vector.z);
  77230. i++;
  77231. }
  77232. return result;
  77233. };
  77234. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77235. var _this = this;
  77236. var numSamples = this.samples;
  77237. this._sampleSphere = this._generateHemisphere();
  77238. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  77239. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77240. "base", "range", "projection", "near", "far", "texelSize",
  77241. "xViewport", "yViewport", "maxZ", "minZAspect"
  77242. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77243. this._ssaoPostProcess.onApply = function (effect) {
  77244. if (_this._firstUpdate) {
  77245. effect.setArray3("sampleSphere", _this._sampleSphere);
  77246. effect.setFloat("randTextureTiles", 32.0);
  77247. }
  77248. if (!_this._scene.activeCamera) {
  77249. return;
  77250. }
  77251. effect.setFloat("samplesFactor", 1 / _this.samples);
  77252. effect.setFloat("totalStrength", _this.totalStrength);
  77253. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  77254. effect.setFloat("radius", _this.radius);
  77255. effect.setFloat("maxZ", _this.maxZ);
  77256. effect.setFloat("minZAspect", _this.minZAspect);
  77257. effect.setFloat("base", _this.base);
  77258. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77259. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77260. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  77261. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  77262. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  77263. effect.setTexture("textureSampler", _this._depthTexture);
  77264. effect.setTexture("normalSampler", _this._normalTexture);
  77265. effect.setTexture("randomSampler", _this._randomTexture);
  77266. };
  77267. this._ssaoPostProcess.samples = this.textureSamples;
  77268. };
  77269. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77270. var _this = this;
  77271. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77272. this._ssaoCombinePostProcess.onApply = function (effect) {
  77273. var viewport = _this._scene.activeCamera.viewport;
  77274. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  77275. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77276. };
  77277. this._ssaoCombinePostProcess.samples = this.textureSamples;
  77278. };
  77279. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  77280. var size = 128;
  77281. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77282. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77283. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77284. var context = this._randomTexture.getContext();
  77285. var rand = function (min, max) {
  77286. return Math.random() * (max - min) + min;
  77287. };
  77288. var randVector = BABYLON.Vector3.Zero();
  77289. for (var x = 0; x < size; x++) {
  77290. for (var y = 0; y < size; y++) {
  77291. randVector.x = rand(0.0, 1.0);
  77292. randVector.y = rand(0.0, 1.0);
  77293. randVector.z = 0.0;
  77294. randVector.normalize();
  77295. randVector.scaleInPlace(255);
  77296. randVector.x = Math.floor(randVector.x);
  77297. randVector.y = Math.floor(randVector.y);
  77298. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77299. context.fillRect(x, y, 1, 1);
  77300. }
  77301. }
  77302. this._randomTexture.update(false);
  77303. };
  77304. /**
  77305. * Serialize the rendering pipeline (Used when exporting)
  77306. * @returns the serialized object
  77307. */
  77308. SSAO2RenderingPipeline.prototype.serialize = function () {
  77309. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77310. serializationObject.customType = "SSAO2RenderingPipeline";
  77311. return serializationObject;
  77312. };
  77313. /**
  77314. * Parse the serialized pipeline
  77315. * @param source Source pipeline.
  77316. * @param scene The scene to load the pipeline to.
  77317. * @param rootUrl The URL of the serialized pipeline.
  77318. * @returns An instantiated pipeline from the serialized object.
  77319. */
  77320. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  77321. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77322. };
  77323. __decorate([
  77324. BABYLON.serialize()
  77325. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  77326. __decorate([
  77327. BABYLON.serialize()
  77328. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  77329. __decorate([
  77330. BABYLON.serialize()
  77331. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  77332. __decorate([
  77333. BABYLON.serialize("samples")
  77334. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  77335. __decorate([
  77336. BABYLON.serialize("textureSamples")
  77337. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  77338. __decorate([
  77339. BABYLON.serialize()
  77340. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  77341. __decorate([
  77342. BABYLON.serialize("expensiveBlur")
  77343. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  77344. __decorate([
  77345. BABYLON.serialize()
  77346. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  77347. __decorate([
  77348. BABYLON.serialize()
  77349. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  77350. return SSAO2RenderingPipeline;
  77351. }(BABYLON.PostProcessRenderPipeline));
  77352. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  77353. })(BABYLON || (BABYLON = {}));
  77354. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  77355. // BABYLON.JS Chromatic Aberration GLSL Shader
  77356. // Author: Olivier Guyot
  77357. // Separates very slightly R, G and B colors on the edges of the screen
  77358. // Inspired by Francois Tarlier & Martins Upitis
  77359. var BABYLON;
  77360. (function (BABYLON) {
  77361. var LensRenderingPipeline = /** @class */ (function (_super) {
  77362. __extends(LensRenderingPipeline, _super);
  77363. /**
  77364. * @constructor
  77365. *
  77366. * Effect parameters are as follow:
  77367. * {
  77368. * chromatic_aberration: number; // from 0 to x (1 for realism)
  77369. * edge_blur: number; // from 0 to x (1 for realism)
  77370. * distortion: number; // from 0 to x (1 for realism)
  77371. * grain_amount: number; // from 0 to 1
  77372. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  77373. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  77374. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  77375. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  77376. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  77377. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  77378. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  77379. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  77380. * }
  77381. * Note: if an effect parameter is unset, effect is disabled
  77382. *
  77383. * @param {string} name - The rendering pipeline name
  77384. * @param {object} parameters - An object containing all parameters (see above)
  77385. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77386. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  77387. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77388. */
  77389. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  77390. if (ratio === void 0) { ratio = 1.0; }
  77391. var _this = _super.call(this, scene.getEngine(), name) || this;
  77392. // Lens effects can be of the following:
  77393. // - chromatic aberration (slight shift of RGB colors)
  77394. // - blur on the edge of the lens
  77395. // - lens distortion
  77396. // - depth-of-field blur & highlights enhancing
  77397. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  77398. // - grain effect (noise or custom texture)
  77399. // Two additional texture samplers are needed:
  77400. // - depth map (for depth-of-field)
  77401. // - grain texture
  77402. /**
  77403. * The chromatic aberration PostProcess id in the pipeline
  77404. */
  77405. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  77406. /**
  77407. * The highlights enhancing PostProcess id in the pipeline
  77408. */
  77409. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  77410. /**
  77411. * The depth-of-field PostProcess id in the pipeline
  77412. */
  77413. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  77414. _this._scene = scene;
  77415. // Fetch texture samplers
  77416. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77417. if (parameters.grain_texture) {
  77418. _this._grainTexture = parameters.grain_texture;
  77419. }
  77420. else {
  77421. _this._createGrainTexture();
  77422. }
  77423. // save parameters
  77424. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  77425. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  77426. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  77427. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  77428. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  77429. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  77430. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  77431. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  77432. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  77433. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  77434. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  77435. // Create effects
  77436. _this._createChromaticAberrationPostProcess(ratio);
  77437. _this._createHighlightsPostProcess(ratio);
  77438. _this._createDepthOfFieldPostProcess(ratio / 4);
  77439. // Set up pipeline
  77440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  77441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  77442. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  77443. if (_this._highlightsGain === -1) {
  77444. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  77445. }
  77446. // Finish
  77447. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77448. if (cameras) {
  77449. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77450. }
  77451. return _this;
  77452. }
  77453. // public methods (self explanatory)
  77454. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  77455. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  77456. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  77457. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  77458. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  77459. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  77460. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  77461. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  77462. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  77463. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  77464. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  77465. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  77466. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  77467. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  77468. };
  77469. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  77470. this._highlightsPostProcess.updateEffect();
  77471. };
  77472. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  77473. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  77474. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  77475. this._highlightsGain = amount;
  77476. };
  77477. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  77478. if (this._highlightsGain === -1) {
  77479. this._highlightsGain = 1.0;
  77480. }
  77481. this._highlightsThreshold = amount;
  77482. };
  77483. LensRenderingPipeline.prototype.disableHighlights = function () {
  77484. this._highlightsGain = -1;
  77485. };
  77486. /**
  77487. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  77488. */
  77489. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77490. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77491. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77492. this._chromaticAberrationPostProcess = null;
  77493. this._highlightsPostProcess = null;
  77494. this._depthOfFieldPostProcess = null;
  77495. this._grainTexture.dispose();
  77496. if (disableDepthRender)
  77497. this._scene.disableDepthRenderer();
  77498. };
  77499. // colors shifting and distortion
  77500. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77501. var _this = this;
  77502. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77503. [], // samplers
  77504. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77505. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77506. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77507. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77508. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77509. effect.setFloat('radialIntensity', 1);
  77510. effect.setFloat2('direction', 17, 17);
  77511. effect.setFloat2('centerPosition', 0.5, 0.5);
  77512. };
  77513. };
  77514. // highlights enhancing
  77515. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  77516. var _this = this;
  77517. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  77518. [], // samplers
  77519. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  77520. this._highlightsPostProcess.onApply = function (effect) {
  77521. effect.setFloat('gain', _this._highlightsGain);
  77522. effect.setFloat('threshold', _this._highlightsThreshold);
  77523. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  77524. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77525. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77526. };
  77527. };
  77528. // colors shifting and distortion
  77529. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  77530. var _this = this;
  77531. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  77532. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  77533. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  77534. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77535. this._depthOfFieldPostProcess.onApply = function (effect) {
  77536. effect.setTexture("depthSampler", _this._depthTexture);
  77537. effect.setTexture("grainSampler", _this._grainTexture);
  77538. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  77539. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  77540. effect.setFloat('grain_amount', _this._grainAmount);
  77541. effect.setBool('blur_noise', _this._blurNoise);
  77542. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77543. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77544. effect.setFloat('distortion', _this._distortion);
  77545. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  77546. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  77547. effect.setFloat('aperture', _this._dofAperture);
  77548. effect.setFloat('darken', _this._dofDarken);
  77549. effect.setFloat('edge_blur', _this._edgeBlur);
  77550. effect.setBool('highlights', (_this._highlightsGain !== -1));
  77551. if (_this._scene.activeCamera) {
  77552. effect.setFloat('near', _this._scene.activeCamera.minZ);
  77553. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  77554. }
  77555. };
  77556. };
  77557. // creates a black and white random noise texture, 512x512
  77558. LensRenderingPipeline.prototype._createGrainTexture = function () {
  77559. var size = 512;
  77560. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77561. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77562. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77563. var context = this._grainTexture.getContext();
  77564. var rand = function (min, max) {
  77565. return Math.random() * (max - min) + min;
  77566. };
  77567. var value;
  77568. for (var x = 0; x < size; x++) {
  77569. for (var y = 0; y < size; y++) {
  77570. value = Math.floor(rand(0.42, 0.58) * 255);
  77571. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  77572. context.fillRect(x, y, 1, 1);
  77573. }
  77574. }
  77575. this._grainTexture.update(false);
  77576. };
  77577. return LensRenderingPipeline;
  77578. }(BABYLON.PostProcessRenderPipeline));
  77579. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  77580. })(BABYLON || (BABYLON = {}));
  77581. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  77582. var BABYLON;
  77583. (function (BABYLON) {
  77584. var StandardRenderingPipeline = /** @class */ (function (_super) {
  77585. __extends(StandardRenderingPipeline, _super);
  77586. /**
  77587. * @constructor
  77588. * @param {string} name - The rendering pipeline name
  77589. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77590. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  77591. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  77592. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77593. */
  77594. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  77595. if (originalPostProcess === void 0) { originalPostProcess = null; }
  77596. var _this = _super.call(this, scene.getEngine(), name) || this;
  77597. _this.downSampleX4PostProcess = null;
  77598. _this.brightPassPostProcess = null;
  77599. _this.blurHPostProcesses = [];
  77600. _this.blurVPostProcesses = [];
  77601. _this.textureAdderPostProcess = null;
  77602. _this.volumetricLightPostProcess = null;
  77603. _this.volumetricLightSmoothXPostProcess = null;
  77604. _this.volumetricLightSmoothYPostProcess = null;
  77605. _this.volumetricLightMergePostProces = null;
  77606. _this.volumetricLightFinalPostProcess = null;
  77607. _this.luminancePostProcess = null;
  77608. _this.luminanceDownSamplePostProcesses = [];
  77609. _this.hdrPostProcess = null;
  77610. _this.textureAdderFinalPostProcess = null;
  77611. _this.lensFlareFinalPostProcess = null;
  77612. _this.hdrFinalPostProcess = null;
  77613. _this.lensFlarePostProcess = null;
  77614. _this.lensFlareComposePostProcess = null;
  77615. _this.motionBlurPostProcess = null;
  77616. _this.depthOfFieldPostProcess = null;
  77617. // Values
  77618. _this.brightThreshold = 1.0;
  77619. _this.blurWidth = 512.0;
  77620. _this.horizontalBlur = false;
  77621. _this.exposure = 1.0;
  77622. _this.lensTexture = null;
  77623. _this.volumetricLightCoefficient = 0.2;
  77624. _this.volumetricLightPower = 4.0;
  77625. _this.volumetricLightBlurScale = 64.0;
  77626. _this.sourceLight = null;
  77627. _this.hdrMinimumLuminance = 1.0;
  77628. _this.hdrDecreaseRate = 0.5;
  77629. _this.hdrIncreaseRate = 0.5;
  77630. _this.lensColorTexture = null;
  77631. _this.lensFlareStrength = 20.0;
  77632. _this.lensFlareGhostDispersal = 1.4;
  77633. _this.lensFlareHaloWidth = 0.7;
  77634. _this.lensFlareDistortionStrength = 16.0;
  77635. _this.lensStarTexture = null;
  77636. _this.lensFlareDirtTexture = null;
  77637. _this.depthOfFieldDistance = 10.0;
  77638. _this.depthOfFieldBlurWidth = 64.0;
  77639. _this.motionStrength = 1.0;
  77640. // IAnimatable
  77641. _this.animations = [];
  77642. _this._currentDepthOfFieldSource = null;
  77643. _this._hdrCurrentLuminance = 1.0;
  77644. // Getters and setters
  77645. _this._bloomEnabled = true;
  77646. _this._depthOfFieldEnabled = false;
  77647. _this._vlsEnabled = false;
  77648. _this._lensFlareEnabled = false;
  77649. _this._hdrEnabled = false;
  77650. _this._motionBlurEnabled = false;
  77651. _this._motionBlurSamples = 64.0;
  77652. _this._volumetricLightStepsCount = 50.0;
  77653. _this._cameras = cameras || [];
  77654. // Initialize
  77655. _this._scene = scene;
  77656. _this._basePostProcess = originalPostProcess;
  77657. _this._ratio = ratio;
  77658. // Misc
  77659. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77660. // Finish
  77661. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77662. _this._buildPipeline();
  77663. return _this;
  77664. }
  77665. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  77666. get: function () {
  77667. return this._bloomEnabled;
  77668. },
  77669. set: function (enabled) {
  77670. if (this._bloomEnabled === enabled) {
  77671. return;
  77672. }
  77673. this._bloomEnabled = enabled;
  77674. this._buildPipeline();
  77675. },
  77676. enumerable: true,
  77677. configurable: true
  77678. });
  77679. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  77680. get: function () {
  77681. return this._depthOfFieldEnabled;
  77682. },
  77683. set: function (enabled) {
  77684. if (this._depthOfFieldEnabled === enabled) {
  77685. return;
  77686. }
  77687. this._depthOfFieldEnabled = enabled;
  77688. this._buildPipeline();
  77689. },
  77690. enumerable: true,
  77691. configurable: true
  77692. });
  77693. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  77694. get: function () {
  77695. return this._lensFlareEnabled;
  77696. },
  77697. set: function (enabled) {
  77698. if (this._lensFlareEnabled === enabled) {
  77699. return;
  77700. }
  77701. this._lensFlareEnabled = enabled;
  77702. this._buildPipeline();
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  77708. get: function () {
  77709. return this._hdrEnabled;
  77710. },
  77711. set: function (enabled) {
  77712. if (this._hdrEnabled === enabled) {
  77713. return;
  77714. }
  77715. this._hdrEnabled = enabled;
  77716. this._buildPipeline();
  77717. },
  77718. enumerable: true,
  77719. configurable: true
  77720. });
  77721. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  77722. get: function () {
  77723. return this._vlsEnabled;
  77724. },
  77725. set: function (enabled) {
  77726. if (this._vlsEnabled === enabled) {
  77727. return;
  77728. }
  77729. if (enabled) {
  77730. var geometry = this._scene.enableGeometryBufferRenderer();
  77731. if (!geometry) {
  77732. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  77733. return;
  77734. }
  77735. }
  77736. this._vlsEnabled = enabled;
  77737. this._buildPipeline();
  77738. },
  77739. enumerable: true,
  77740. configurable: true
  77741. });
  77742. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  77743. get: function () {
  77744. return this._motionBlurEnabled;
  77745. },
  77746. set: function (enabled) {
  77747. if (this._motionBlurEnabled === enabled) {
  77748. return;
  77749. }
  77750. this._motionBlurEnabled = enabled;
  77751. this._buildPipeline();
  77752. },
  77753. enumerable: true,
  77754. configurable: true
  77755. });
  77756. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  77757. get: function () {
  77758. return this._volumetricLightStepsCount;
  77759. },
  77760. set: function (count) {
  77761. if (this.volumetricLightPostProcess) {
  77762. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  77763. }
  77764. this._volumetricLightStepsCount = count;
  77765. },
  77766. enumerable: true,
  77767. configurable: true
  77768. });
  77769. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  77770. get: function () {
  77771. return this._motionBlurSamples;
  77772. },
  77773. set: function (samples) {
  77774. if (this.motionBlurPostProcess) {
  77775. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  77776. }
  77777. this._motionBlurSamples = samples;
  77778. },
  77779. enumerable: true,
  77780. configurable: true
  77781. });
  77782. StandardRenderingPipeline.prototype._buildPipeline = function () {
  77783. var _this = this;
  77784. var ratio = this._ratio;
  77785. var scene = this._scene;
  77786. this._disposePostProcesses();
  77787. this._reset();
  77788. // Create pass post-process
  77789. if (!this._basePostProcess) {
  77790. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  77791. this.originalPostProcess.onApply = function (effect) {
  77792. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  77793. };
  77794. }
  77795. else {
  77796. this.originalPostProcess = this._basePostProcess;
  77797. }
  77798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  77799. this._currentDepthOfFieldSource = this.originalPostProcess;
  77800. if (this._bloomEnabled) {
  77801. // Create down sample X4 post-process
  77802. this._createDownSampleX4PostProcess(scene, ratio / 2);
  77803. // Create bright pass post-process
  77804. this._createBrightPassPostProcess(scene, ratio / 2);
  77805. // Create gaussian blur post-processes (down sampling blurs)
  77806. this._createBlurPostProcesses(scene, ratio / 4, 1);
  77807. // Create texture adder post-process
  77808. this._createTextureAdderPostProcess(scene, ratio);
  77809. // Create depth-of-field source post-process
  77810. 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);
  77811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  77812. }
  77813. if (this._vlsEnabled) {
  77814. // Create volumetric light
  77815. this._createVolumetricLightPostProcess(scene, ratio);
  77816. // Create volumetric light final post-process
  77817. 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);
  77818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  77819. }
  77820. if (this._lensFlareEnabled) {
  77821. // Create lens flare post-process
  77822. this._createLensFlarePostProcess(scene, ratio);
  77823. // Create depth-of-field source post-process post lens-flare and disable it now
  77824. 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);
  77825. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  77826. }
  77827. if (this._hdrEnabled) {
  77828. // Create luminance
  77829. this._createLuminancePostProcesses(scene, this._floatTextureType);
  77830. // Create HDR
  77831. this._createHdrPostProcess(scene, ratio);
  77832. // Create depth-of-field source post-process post hdr and disable it now
  77833. 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);
  77834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  77835. }
  77836. if (this._depthOfFieldEnabled) {
  77837. // Create gaussian blur used by depth-of-field
  77838. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  77839. // Create depth-of-field post-process
  77840. this._createDepthOfFieldPostProcess(scene, ratio);
  77841. }
  77842. if (this._motionBlurEnabled) {
  77843. // Create motion blur post-process
  77844. this._createMotionBlurPostProcess(scene, ratio);
  77845. }
  77846. if (this._cameras !== null) {
  77847. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  77848. }
  77849. };
  77850. // Down Sample X4 Post-Processs
  77851. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  77852. var _this = this;
  77853. var downSampleX4Offsets = new Array(32);
  77854. 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);
  77855. this.downSampleX4PostProcess.onApply = function (effect) {
  77856. var id = 0;
  77857. var width = _this.downSampleX4PostProcess.width;
  77858. var height = _this.downSampleX4PostProcess.height;
  77859. for (var i = -2; i < 2; i++) {
  77860. for (var j = -2; j < 2; j++) {
  77861. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  77862. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  77863. id += 2;
  77864. }
  77865. }
  77866. effect.setArray2("dsOffsets", downSampleX4Offsets);
  77867. };
  77868. // Add to pipeline
  77869. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  77870. };
  77871. // Brightpass Post-Process
  77872. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  77873. var _this = this;
  77874. var brightOffsets = new Array(8);
  77875. 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);
  77876. this.brightPassPostProcess.onApply = function (effect) {
  77877. var sU = (1.0 / _this.brightPassPostProcess.width);
  77878. var sV = (1.0 / _this.brightPassPostProcess.height);
  77879. brightOffsets[0] = -0.5 * sU;
  77880. brightOffsets[1] = 0.5 * sV;
  77881. brightOffsets[2] = 0.5 * sU;
  77882. brightOffsets[3] = 0.5 * sV;
  77883. brightOffsets[4] = -0.5 * sU;
  77884. brightOffsets[5] = -0.5 * sV;
  77885. brightOffsets[6] = 0.5 * sU;
  77886. brightOffsets[7] = -0.5 * sV;
  77887. effect.setArray2("dsOffsets", brightOffsets);
  77888. effect.setFloat("brightThreshold", _this.brightThreshold);
  77889. };
  77890. // Add to pipeline
  77891. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  77892. };
  77893. // Create blur H&V post-processes
  77894. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  77895. var _this = this;
  77896. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  77897. var engine = scene.getEngine();
  77898. 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);
  77899. 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);
  77900. blurX.onActivateObservable.add(function () {
  77901. var dw = blurX.width / engine.getRenderWidth();
  77902. blurX.kernel = _this[blurWidthKey] * dw;
  77903. });
  77904. blurY.onActivateObservable.add(function () {
  77905. var dw = blurY.height / engine.getRenderHeight();
  77906. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  77907. });
  77908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  77909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  77910. this.blurHPostProcesses.push(blurX);
  77911. this.blurVPostProcesses.push(blurY);
  77912. };
  77913. // Create texture adder post-process
  77914. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  77915. var _this = this;
  77916. 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);
  77917. this.textureAdderPostProcess.onApply = function (effect) {
  77918. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  77919. effect.setTexture("lensSampler", _this.lensTexture);
  77920. effect.setFloat("exposure", _this.exposure);
  77921. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  77922. };
  77923. // Add to pipeline
  77924. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  77925. };
  77926. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  77927. var _this = this;
  77928. var geometryRenderer = scene.enableGeometryBufferRenderer();
  77929. geometryRenderer.enablePosition = true;
  77930. var geometry = geometryRenderer.getGBuffer();
  77931. // Base post-process
  77932. 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));
  77933. var depthValues = BABYLON.Vector2.Zero();
  77934. this.volumetricLightPostProcess.onApply = function (effect) {
  77935. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  77936. var generator = _this.sourceLight.getShadowGenerator();
  77937. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  77938. effect.setTexture("positionSampler", geometry.textures[2]);
  77939. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  77940. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  77941. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  77942. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  77943. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  77944. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  77945. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  77946. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  77947. effect.setVector2("depthValues", depthValues);
  77948. }
  77949. };
  77950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  77951. // Smooth
  77952. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  77953. // Merge
  77954. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  77955. this.volumetricLightMergePostProces.onApply = function (effect) {
  77956. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  77957. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  77958. };
  77959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  77960. };
  77961. // Create luminance
  77962. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  77963. var _this = this;
  77964. // Create luminance
  77965. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  77966. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  77967. var offsets = [];
  77968. this.luminancePostProcess.onApply = function (effect) {
  77969. var sU = (1.0 / _this.luminancePostProcess.width);
  77970. var sV = (1.0 / _this.luminancePostProcess.height);
  77971. offsets[0] = -0.5 * sU;
  77972. offsets[1] = 0.5 * sV;
  77973. offsets[2] = 0.5 * sU;
  77974. offsets[3] = 0.5 * sV;
  77975. offsets[4] = -0.5 * sU;
  77976. offsets[5] = -0.5 * sV;
  77977. offsets[6] = 0.5 * sU;
  77978. offsets[7] = -0.5 * sV;
  77979. effect.setArray2("lumOffsets", offsets);
  77980. };
  77981. // Add to pipeline
  77982. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  77983. // Create down sample luminance
  77984. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  77985. var size = Math.pow(3, i);
  77986. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  77987. if (i === 0) {
  77988. defines += "#define FINAL_DOWN_SAMPLER";
  77989. }
  77990. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  77991. this.luminanceDownSamplePostProcesses.push(postProcess);
  77992. }
  77993. // Create callbacks and add effects
  77994. var lastLuminance = this.luminancePostProcess;
  77995. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  77996. var downSampleOffsets = new Array(18);
  77997. pp.onApply = function (effect) {
  77998. if (!lastLuminance) {
  77999. return;
  78000. }
  78001. var id = 0;
  78002. for (var x = -1; x < 2; x++) {
  78003. for (var y = -1; y < 2; y++) {
  78004. downSampleOffsets[id] = x / lastLuminance.width;
  78005. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78006. id += 2;
  78007. }
  78008. }
  78009. effect.setArray2("dsOffsets", downSampleOffsets);
  78010. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78011. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78012. lastLuminance = _this.luminancePostProcess;
  78013. }
  78014. else {
  78015. lastLuminance = pp;
  78016. }
  78017. };
  78018. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78019. pp.onAfterRender = function (effect) {
  78020. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78021. 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);
  78022. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78023. };
  78024. }
  78025. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78026. });
  78027. };
  78028. // Create HDR post-process
  78029. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78030. var _this = this;
  78031. 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);
  78032. var outputLiminance = 1;
  78033. var time = 0;
  78034. var lastTime = 0;
  78035. this.hdrPostProcess.onApply = function (effect) {
  78036. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78037. time += scene.getEngine().getDeltaTime();
  78038. if (outputLiminance < 0) {
  78039. outputLiminance = _this._hdrCurrentLuminance;
  78040. }
  78041. else {
  78042. var dt = (lastTime - time) / 1000.0;
  78043. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78044. outputLiminance += _this.hdrDecreaseRate * dt;
  78045. }
  78046. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78047. outputLiminance -= _this.hdrIncreaseRate * dt;
  78048. }
  78049. else {
  78050. outputLiminance = _this._hdrCurrentLuminance;
  78051. }
  78052. }
  78053. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78054. effect.setFloat("averageLuminance", outputLiminance);
  78055. lastTime = time;
  78056. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78057. };
  78058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78059. };
  78060. // Create lens flare post-process
  78061. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78062. var _this = this;
  78063. 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);
  78064. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78065. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78066. 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);
  78067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78068. var resolution = new BABYLON.Vector2(0, 0);
  78069. // Lens flare
  78070. this.lensFlarePostProcess.onApply = function (effect) {
  78071. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78072. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78073. effect.setFloat("strength", _this.lensFlareStrength);
  78074. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78075. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78076. // Shift
  78077. resolution.x = _this.lensFlarePostProcess.width;
  78078. resolution.y = _this.lensFlarePostProcess.height;
  78079. effect.setVector2("resolution", resolution);
  78080. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78081. };
  78082. // Compose
  78083. 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);
  78084. 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);
  78085. this.lensFlareComposePostProcess.onApply = function (effect) {
  78086. if (!_this._scene.activeCamera) {
  78087. return;
  78088. }
  78089. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78090. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  78091. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  78092. // Lens start rotation matrix
  78093. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  78094. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  78095. 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));
  78096. camRot *= 4.0;
  78097. 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);
  78098. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  78099. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  78100. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  78101. };
  78102. };
  78103. // Create depth-of-field post-process
  78104. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  78105. var _this = this;
  78106. 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);
  78107. this.depthOfFieldPostProcess.onApply = function (effect) {
  78108. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78109. effect.setTexture("depthSampler", _this._getDepthTexture());
  78110. effect.setFloat("distance", _this.depthOfFieldDistance);
  78111. };
  78112. // Add to pipeline
  78113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  78114. };
  78115. // Create motion blur post-process
  78116. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  78117. var _this = this;
  78118. 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);
  78119. var motionScale = 0;
  78120. var prevViewProjection = BABYLON.Matrix.Identity();
  78121. var invViewProjection = BABYLON.Matrix.Identity();
  78122. var viewProjection = BABYLON.Matrix.Identity();
  78123. var screenSize = BABYLON.Vector2.Zero();
  78124. this.motionBlurPostProcess.onApply = function (effect) {
  78125. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  78126. viewProjection.invertToRef(invViewProjection);
  78127. effect.setMatrix("inverseViewProjection", invViewProjection);
  78128. effect.setMatrix("prevViewProjection", prevViewProjection);
  78129. prevViewProjection = viewProjection;
  78130. screenSize.x = _this.motionBlurPostProcess.width;
  78131. screenSize.y = _this.motionBlurPostProcess.height;
  78132. effect.setVector2("screenSize", screenSize);
  78133. motionScale = scene.getEngine().getFps() / 60.0;
  78134. effect.setFloat("motionScale", motionScale);
  78135. effect.setFloat("motionStrength", _this.motionStrength);
  78136. effect.setTexture("depthSampler", _this._getDepthTexture());
  78137. };
  78138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  78139. };
  78140. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  78141. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  78142. var renderer = this._scene.enableGeometryBufferRenderer();
  78143. return renderer.getGBuffer().textures[0];
  78144. }
  78145. return this._scene.enableDepthRenderer().getDepthMap();
  78146. };
  78147. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  78148. for (var i = 0; i < this._cameras.length; i++) {
  78149. var camera = this._cameras[i];
  78150. if (this.originalPostProcess) {
  78151. this.originalPostProcess.dispose(camera);
  78152. }
  78153. if (this.downSampleX4PostProcess) {
  78154. this.downSampleX4PostProcess.dispose(camera);
  78155. }
  78156. if (this.brightPassPostProcess) {
  78157. this.brightPassPostProcess.dispose(camera);
  78158. }
  78159. if (this.textureAdderPostProcess) {
  78160. this.textureAdderPostProcess.dispose(camera);
  78161. }
  78162. if (this.textureAdderFinalPostProcess) {
  78163. this.textureAdderFinalPostProcess.dispose(camera);
  78164. }
  78165. if (this.volumetricLightPostProcess) {
  78166. this.volumetricLightPostProcess.dispose(camera);
  78167. }
  78168. if (this.volumetricLightSmoothXPostProcess) {
  78169. this.volumetricLightSmoothXPostProcess.dispose(camera);
  78170. }
  78171. if (this.volumetricLightSmoothYPostProcess) {
  78172. this.volumetricLightSmoothYPostProcess.dispose(camera);
  78173. }
  78174. if (this.volumetricLightMergePostProces) {
  78175. this.volumetricLightMergePostProces.dispose(camera);
  78176. }
  78177. if (this.volumetricLightFinalPostProcess) {
  78178. this.volumetricLightFinalPostProcess.dispose(camera);
  78179. }
  78180. if (this.lensFlarePostProcess) {
  78181. this.lensFlarePostProcess.dispose(camera);
  78182. }
  78183. if (this.lensFlareComposePostProcess) {
  78184. this.lensFlareComposePostProcess.dispose(camera);
  78185. }
  78186. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  78187. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  78188. }
  78189. if (this.luminancePostProcess) {
  78190. this.luminancePostProcess.dispose(camera);
  78191. }
  78192. if (this.hdrPostProcess) {
  78193. this.hdrPostProcess.dispose(camera);
  78194. }
  78195. if (this.hdrFinalPostProcess) {
  78196. this.hdrFinalPostProcess.dispose(camera);
  78197. }
  78198. if (this.depthOfFieldPostProcess) {
  78199. this.depthOfFieldPostProcess.dispose(camera);
  78200. }
  78201. if (this.motionBlurPostProcess) {
  78202. this.motionBlurPostProcess.dispose(camera);
  78203. }
  78204. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  78205. this.blurHPostProcesses[j].dispose(camera);
  78206. }
  78207. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  78208. this.blurVPostProcesses[j].dispose(camera);
  78209. }
  78210. }
  78211. this.originalPostProcess = null;
  78212. this.downSampleX4PostProcess = null;
  78213. this.brightPassPostProcess = null;
  78214. this.textureAdderPostProcess = null;
  78215. this.textureAdderFinalPostProcess = null;
  78216. this.volumetricLightPostProcess = null;
  78217. this.volumetricLightSmoothXPostProcess = null;
  78218. this.volumetricLightSmoothYPostProcess = null;
  78219. this.volumetricLightMergePostProces = null;
  78220. this.volumetricLightFinalPostProcess = null;
  78221. this.lensFlarePostProcess = null;
  78222. this.lensFlareComposePostProcess = null;
  78223. this.luminancePostProcess = null;
  78224. this.hdrPostProcess = null;
  78225. this.hdrFinalPostProcess = null;
  78226. this.depthOfFieldPostProcess = null;
  78227. this.motionBlurPostProcess = null;
  78228. this.luminanceDownSamplePostProcesses = [];
  78229. this.blurHPostProcesses = [];
  78230. this.blurVPostProcesses = [];
  78231. };
  78232. /**
  78233. * Dispose of the pipeline and stop all post processes
  78234. */
  78235. StandardRenderingPipeline.prototype.dispose = function () {
  78236. this._disposePostProcesses();
  78237. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78238. _super.prototype.dispose.call(this);
  78239. };
  78240. /**
  78241. * Serialize the rendering pipeline (Used when exporting)
  78242. * @returns the serialized object
  78243. */
  78244. StandardRenderingPipeline.prototype.serialize = function () {
  78245. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78246. if (this.sourceLight) {
  78247. serializationObject.sourceLightId = this.sourceLight.id;
  78248. }
  78249. serializationObject.customType = "StandardRenderingPipeline";
  78250. return serializationObject;
  78251. };
  78252. /**
  78253. * Parse the serialized pipeline
  78254. * @param source Source pipeline.
  78255. * @param scene The scene to load the pipeline to.
  78256. * @param rootUrl The URL of the serialized pipeline.
  78257. * @returns An instantiated pipeline from the serialized object.
  78258. */
  78259. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78260. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78261. if (source.sourceLightId) {
  78262. p.sourceLight = scene.getLightByID(source.sourceLightId);
  78263. }
  78264. return p;
  78265. };
  78266. // Luminance steps
  78267. StandardRenderingPipeline.LuminanceSteps = 6;
  78268. __decorate([
  78269. BABYLON.serialize()
  78270. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  78271. __decorate([
  78272. BABYLON.serialize()
  78273. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  78274. __decorate([
  78275. BABYLON.serialize()
  78276. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  78277. __decorate([
  78278. BABYLON.serialize()
  78279. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  78280. __decorate([
  78281. BABYLON.serializeAsTexture("lensTexture")
  78282. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  78283. __decorate([
  78284. BABYLON.serialize()
  78285. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  78286. __decorate([
  78287. BABYLON.serialize()
  78288. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  78289. __decorate([
  78290. BABYLON.serialize()
  78291. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  78292. __decorate([
  78293. BABYLON.serialize()
  78294. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  78295. __decorate([
  78296. BABYLON.serialize()
  78297. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  78298. __decorate([
  78299. BABYLON.serialize()
  78300. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  78301. __decorate([
  78302. BABYLON.serializeAsTexture("lensColorTexture")
  78303. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  78304. __decorate([
  78305. BABYLON.serialize()
  78306. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  78307. __decorate([
  78308. BABYLON.serialize()
  78309. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  78310. __decorate([
  78311. BABYLON.serialize()
  78312. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  78313. __decorate([
  78314. BABYLON.serialize()
  78315. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  78316. __decorate([
  78317. BABYLON.serializeAsTexture("lensStarTexture")
  78318. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  78319. __decorate([
  78320. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  78321. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  78322. __decorate([
  78323. BABYLON.serialize()
  78324. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  78325. __decorate([
  78326. BABYLON.serialize()
  78327. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  78328. __decorate([
  78329. BABYLON.serialize()
  78330. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  78331. __decorate([
  78332. BABYLON.serialize()
  78333. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  78334. __decorate([
  78335. BABYLON.serialize()
  78336. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  78337. __decorate([
  78338. BABYLON.serialize()
  78339. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  78340. __decorate([
  78341. BABYLON.serialize()
  78342. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  78343. __decorate([
  78344. BABYLON.serialize()
  78345. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  78346. __decorate([
  78347. BABYLON.serialize()
  78348. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  78349. __decorate([
  78350. BABYLON.serialize()
  78351. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  78352. __decorate([
  78353. BABYLON.serialize()
  78354. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  78355. __decorate([
  78356. BABYLON.serialize()
  78357. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  78358. return StandardRenderingPipeline;
  78359. }(BABYLON.PostProcessRenderPipeline));
  78360. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  78361. })(BABYLON || (BABYLON = {}));
  78362. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  78363. var BABYLON;
  78364. (function (BABYLON) {
  78365. var FxaaPostProcess = /** @class */ (function (_super) {
  78366. __extends(FxaaPostProcess, _super);
  78367. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78368. if (camera === void 0) { camera = null; }
  78369. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78370. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  78371. var defines = _this._getDefines();
  78372. _this.updateEffect(defines);
  78373. _this.onApplyObservable.add(function (effect) {
  78374. var texelSize = _this.texelSize;
  78375. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  78376. });
  78377. return _this;
  78378. }
  78379. FxaaPostProcess.prototype._getDefines = function () {
  78380. var engine = this.getEngine();
  78381. if (!engine) {
  78382. return null;
  78383. }
  78384. var glInfo = engine.getGlInfo();
  78385. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  78386. return "#define MALI 1\n";
  78387. }
  78388. return null;
  78389. };
  78390. return FxaaPostProcess;
  78391. }(BABYLON.PostProcess));
  78392. BABYLON.FxaaPostProcess = FxaaPostProcess;
  78393. })(BABYLON || (BABYLON = {}));
  78394. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  78395. var BABYLON;
  78396. (function (BABYLON) {
  78397. /**
  78398. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  78399. */
  78400. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  78401. __extends(ChromaticAberrationPostProcess, _super);
  78402. /**
  78403. * Creates a new instance ChromaticAberrationPostProcess
  78404. * @param name The name of the effect.
  78405. * @param screenWidth The width of the screen to apply the effect on.
  78406. * @param screenHeight The height of the screen to apply the effect on.
  78407. * @param options The required width/height ratio to downsize to before computing the render pass.
  78408. * @param camera The camera to apply the render pass to.
  78409. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78410. * @param engine The engine which the post process will be applied. (default: current engine)
  78411. * @param reusable If the post process can be reused on the same frame. (default: false)
  78412. * @param textureType Type of textures used when performing the post process. (default: 0)
  78413. * @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)
  78414. */
  78415. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78417. if (blockCompilation === void 0) { blockCompilation = false; }
  78418. 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;
  78419. /**
  78420. * The amount of seperation of rgb channels (default: 30)
  78421. */
  78422. _this.aberrationAmount = 30;
  78423. /**
  78424. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  78425. */
  78426. _this.radialIntensity = 0;
  78427. /**
  78428. * 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))
  78429. */
  78430. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  78431. /**
  78432. * 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))
  78433. */
  78434. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  78435. _this.onApplyObservable.add(function (effect) {
  78436. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  78437. effect.setFloat('screen_width', screenWidth);
  78438. effect.setFloat('screen_height', screenHeight);
  78439. effect.setFloat('radialIntensity', _this.radialIntensity);
  78440. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  78441. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  78442. });
  78443. return _this;
  78444. }
  78445. return ChromaticAberrationPostProcess;
  78446. }(BABYLON.PostProcess));
  78447. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  78448. })(BABYLON || (BABYLON = {}));
  78449. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  78450. var BABYLON;
  78451. (function (BABYLON) {
  78452. /**
  78453. * The GrainPostProcess adds noise to the image at mid luminance levels
  78454. */
  78455. var GrainPostProcess = /** @class */ (function (_super) {
  78456. __extends(GrainPostProcess, _super);
  78457. /**
  78458. * Creates a new instance of @see GrainPostProcess
  78459. * @param name The name of the effect.
  78460. * @param options The required width/height ratio to downsize to before computing the render pass.
  78461. * @param camera The camera to apply the render pass to.
  78462. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78463. * @param engine The engine which the post process will be applied. (default: current engine)
  78464. * @param reusable If the post process can be reused on the same frame. (default: false)
  78465. * @param textureType Type of textures used when performing the post process. (default: 0)
  78466. * @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)
  78467. */
  78468. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78469. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78470. if (blockCompilation === void 0) { blockCompilation = false; }
  78471. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78472. /**
  78473. * The intensity of the grain added (default: 30)
  78474. */
  78475. _this.intensity = 30;
  78476. /**
  78477. * If the grain should be randomized on every frame
  78478. */
  78479. _this.animated = false;
  78480. _this.onApplyObservable.add(function (effect) {
  78481. effect.setFloat('intensity', _this.intensity);
  78482. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  78483. });
  78484. return _this;
  78485. }
  78486. return GrainPostProcess;
  78487. }(BABYLON.PostProcess));
  78488. BABYLON.GrainPostProcess = GrainPostProcess;
  78489. })(BABYLON || (BABYLON = {}));
  78490. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78491. var BABYLON;
  78492. (function (BABYLON) {
  78493. /**
  78494. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78495. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78496. */
  78497. var SharpenPostProcess = /** @class */ (function (_super) {
  78498. __extends(SharpenPostProcess, _super);
  78499. /**
  78500. * Creates a new instance ConvolutionPostProcess
  78501. * @param name The name of the effect.
  78502. * @param options The required width/height ratio to downsize to before computing the render pass.
  78503. * @param camera The camera to apply the render pass to.
  78504. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78505. * @param engine The engine which the post process will be applied. (default: current engine)
  78506. * @param reusable If the post process can be reused on the same frame. (default: false)
  78507. * @param textureType Type of textures used when performing the post process. (default: 0)
  78508. * @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)
  78509. */
  78510. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78511. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78512. if (blockCompilation === void 0) { blockCompilation = false; }
  78513. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78514. /**
  78515. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  78516. */
  78517. _this.colorAmount = 1.0;
  78518. /**
  78519. * How much sharpness should be applied (default: 0.3)
  78520. */
  78521. _this.edgeAmount = 0.3;
  78522. _this.onApply = function (effect) {
  78523. effect.setFloat2("screenSize", _this.width, _this.height);
  78524. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  78525. };
  78526. return _this;
  78527. }
  78528. return SharpenPostProcess;
  78529. }(BABYLON.PostProcess));
  78530. BABYLON.SharpenPostProcess = SharpenPostProcess;
  78531. })(BABYLON || (BABYLON = {}));
  78532. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  78533. var BABYLON;
  78534. (function (BABYLON) {
  78535. /**
  78536. * The Blur Post Process which blurs an image based on a kernel and direction.
  78537. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  78538. */
  78539. var BlurPostProcess = /** @class */ (function (_super) {
  78540. __extends(BlurPostProcess, _super);
  78541. /**
  78542. * Creates a new instance BlurPostProcess
  78543. * @param name The name of the effect.
  78544. * @param direction The direction in which to blur the image.
  78545. * @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.
  78546. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  78547. * @param camera The camera to apply the render pass to.
  78548. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78549. * @param engine The engine which the post process will be applied. (default: current engine)
  78550. * @param reusable If the post process can be reused on the same frame. (default: false)
  78551. * @param textureType Type of textures used when performing the post process. (default: 0)
  78552. * @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)
  78553. */
  78554. function BlurPostProcess(name,
  78555. /** The direction in which to blur the image. */
  78556. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  78557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78558. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78559. if (defines === void 0) { defines = ""; }
  78560. if (blockCompilation === void 0) { blockCompilation = false; }
  78561. 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;
  78562. _this.direction = direction;
  78563. _this.blockCompilation = blockCompilation;
  78564. _this._packedFloat = false;
  78565. _this._staticDefines = "";
  78566. _this._staticDefines = defines;
  78567. _this.onApplyObservable.add(function (effect) {
  78568. if (_this._outputTexture) {
  78569. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  78570. }
  78571. else {
  78572. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  78573. }
  78574. });
  78575. _this.kernel = kernel;
  78576. return _this;
  78577. }
  78578. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  78579. /**
  78580. * Gets the length in pixels of the blur sample region
  78581. */
  78582. get: function () {
  78583. return this._idealKernel;
  78584. },
  78585. /**
  78586. * Sets the length in pixels of the blur sample region
  78587. */
  78588. set: function (v) {
  78589. if (this._idealKernel === v) {
  78590. return;
  78591. }
  78592. v = Math.max(v, 1);
  78593. this._idealKernel = v;
  78594. this._kernel = this._nearestBestKernel(v);
  78595. if (!this.blockCompilation) {
  78596. this._updateParameters();
  78597. }
  78598. },
  78599. enumerable: true,
  78600. configurable: true
  78601. });
  78602. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  78603. /**
  78604. * Gets wether or not the blur is unpacking/repacking floats
  78605. */
  78606. get: function () {
  78607. return this._packedFloat;
  78608. },
  78609. /**
  78610. * Sets wether or not the blur needs to unpack/repack floats
  78611. */
  78612. set: function (v) {
  78613. if (this._packedFloat === v) {
  78614. return;
  78615. }
  78616. this._packedFloat = v;
  78617. if (!this.blockCompilation) {
  78618. this._updateParameters();
  78619. }
  78620. },
  78621. enumerable: true,
  78622. configurable: true
  78623. });
  78624. /**
  78625. * Updates the effect with the current post process compile time values and recompiles the shader.
  78626. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78627. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78628. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78629. * @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
  78630. * @param onCompiled Called when the shader has been compiled.
  78631. * @param onError Called if there is an error when compiling a shader.
  78632. */
  78633. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78634. if (defines === void 0) { defines = null; }
  78635. if (uniforms === void 0) { uniforms = null; }
  78636. if (samplers === void 0) { samplers = null; }
  78637. this._updateParameters(onCompiled, onError);
  78638. };
  78639. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  78640. // Generate sampling offsets and weights
  78641. var N = this._kernel;
  78642. var centerIndex = (N - 1) / 2;
  78643. // Generate Gaussian sampling weights over kernel
  78644. var offsets = [];
  78645. var weights = [];
  78646. var totalWeight = 0;
  78647. for (var i = 0; i < N; i++) {
  78648. var u = i / (N - 1);
  78649. var w = this._gaussianWeight(u * 2.0 - 1);
  78650. offsets[i] = (i - centerIndex);
  78651. weights[i] = w;
  78652. totalWeight += w;
  78653. }
  78654. // Normalize weights
  78655. for (var i = 0; i < weights.length; i++) {
  78656. weights[i] /= totalWeight;
  78657. }
  78658. // Optimize: combine samples to take advantage of hardware linear sampling
  78659. // Walk from left to center, combining pairs (symmetrically)
  78660. var linearSamplingWeights = [];
  78661. var linearSamplingOffsets = [];
  78662. var linearSamplingMap = [];
  78663. for (var i = 0; i <= centerIndex; i += 2) {
  78664. var j = Math.min(i + 1, Math.floor(centerIndex));
  78665. var singleCenterSample = i === j;
  78666. if (singleCenterSample) {
  78667. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78668. }
  78669. else {
  78670. var sharedCell = j === centerIndex;
  78671. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  78672. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  78673. if (offsetLinear === 0) {
  78674. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78675. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  78676. }
  78677. else {
  78678. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  78679. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  78680. }
  78681. }
  78682. }
  78683. for (var i = 0; i < linearSamplingMap.length; i++) {
  78684. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  78685. linearSamplingWeights[i] = linearSamplingMap[i].w;
  78686. }
  78687. // Replace with optimized
  78688. offsets = linearSamplingOffsets;
  78689. weights = linearSamplingWeights;
  78690. // Generate shaders
  78691. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  78692. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  78693. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  78694. var defines = "";
  78695. defines += this._staticDefines;
  78696. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  78697. if (this._staticDefines.indexOf("DOF") != -1) {
  78698. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  78699. varyingCount--;
  78700. }
  78701. for (var i = 0; i < varyingCount; i++) {
  78702. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  78703. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  78704. }
  78705. var depCount = 0;
  78706. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  78707. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  78708. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  78709. depCount++;
  78710. }
  78711. if (this.packedFloat) {
  78712. defines += "#define PACKEDFLOAT 1";
  78713. }
  78714. this.blockCompilation = false;
  78715. _super.prototype.updateEffect.call(this, defines, null, null, {
  78716. varyingCount: varyingCount,
  78717. depCount: depCount
  78718. }, onCompiled, onError);
  78719. };
  78720. /**
  78721. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  78722. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  78723. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  78724. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  78725. * The gaps between physical kernels are compensated for in the weighting of the samples
  78726. * @param idealKernel Ideal blur kernel.
  78727. * @return Nearest best kernel.
  78728. */
  78729. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  78730. var v = Math.round(idealKernel);
  78731. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  78732. var k = _a[_i];
  78733. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  78734. return Math.max(k, 3);
  78735. }
  78736. }
  78737. return Math.max(v, 3);
  78738. };
  78739. /**
  78740. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  78741. * @param x The point on the Gaussian distribution to sample.
  78742. * @return the value of the Gaussian function at x.
  78743. */
  78744. BlurPostProcess.prototype._gaussianWeight = function (x) {
  78745. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  78746. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  78747. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  78748. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  78749. // truncated at around 1.3% of peak strength.
  78750. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  78751. var sigma = (1 / 3);
  78752. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  78753. var exponent = -((x * x) / (2.0 * sigma * sigma));
  78754. var weight = (1.0 / denominator) * Math.exp(exponent);
  78755. return weight;
  78756. };
  78757. /**
  78758. * Generates a string that can be used as a floating point number in GLSL.
  78759. * @param x Value to print.
  78760. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  78761. * @return GLSL float string.
  78762. */
  78763. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  78764. if (decimalFigures === void 0) { decimalFigures = 8; }
  78765. return x.toFixed(decimalFigures).replace(/0+$/, '');
  78766. };
  78767. return BlurPostProcess;
  78768. }(BABYLON.PostProcess));
  78769. BABYLON.BlurPostProcess = BlurPostProcess;
  78770. })(BABYLON || (BABYLON = {}));
  78771. //# sourceMappingURL=babylon.blurPostProcess.js.map
  78772. var BABYLON;
  78773. (function (BABYLON) {
  78774. /**
  78775. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  78776. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  78777. * based on samples that have a large difference in distance than the center pixel.
  78778. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  78779. */
  78780. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  78781. __extends(DepthOfFieldBlurPostProcess, _super);
  78782. /**
  78783. * Creates a new instance CircleOfConfusionPostProcess
  78784. * @param name The name of the effect.
  78785. * @param scene The scene the effect belongs to.
  78786. * @param direction The direction the blur should be applied.
  78787. * @param kernel The size of the kernel used to blur.
  78788. * @param options The required width/height ratio to downsize to before computing the render pass.
  78789. * @param camera The camera to apply the render pass to.
  78790. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  78791. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  78792. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78793. * @param engine The engine which the post process will be applied. (default: current engine)
  78794. * @param reusable If the post process can be reused on the same frame. (default: false)
  78795. * @param textureType Type of textures used when performing the post process. (default: 0)
  78796. * @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)
  78797. */
  78798. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  78799. if (imageToBlur === void 0) { imageToBlur = null; }
  78800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78801. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78802. if (blockCompilation === void 0) { blockCompilation = false; }
  78803. 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;
  78804. _this.direction = direction;
  78805. _this.onApplyObservable.add(function (effect) {
  78806. if (imageToBlur != null) {
  78807. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  78808. }
  78809. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  78810. if (scene.activeCamera) {
  78811. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78812. }
  78813. });
  78814. return _this;
  78815. }
  78816. return DepthOfFieldBlurPostProcess;
  78817. }(BABYLON.BlurPostProcess));
  78818. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  78819. })(BABYLON || (BABYLON = {}));
  78820. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  78821. var BABYLON;
  78822. (function (BABYLON) {
  78823. /**
  78824. * Options to be set when merging outputs from the default pipeline.
  78825. */
  78826. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  78827. function DepthOfFieldMergePostProcessOptions() {
  78828. }
  78829. return DepthOfFieldMergePostProcessOptions;
  78830. }());
  78831. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  78832. /**
  78833. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  78834. */
  78835. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  78836. __extends(DepthOfFieldMergePostProcess, _super);
  78837. /**
  78838. * Creates a new instance of DepthOfFieldMergePostProcess
  78839. * @param name The name of the effect.
  78840. * @param originalFromInput Post process which's input will be used for the merge.
  78841. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  78842. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  78843. * @param options The required width/height ratio to downsize to before computing the render pass.
  78844. * @param camera The camera to apply the render pass to.
  78845. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78846. * @param engine The engine which the post process will be applied. (default: current engine)
  78847. * @param reusable If the post process can be reused on the same frame. (default: false)
  78848. * @param textureType Type of textures used when performing the post process. (default: 0)
  78849. * @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)
  78850. */
  78851. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78852. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78853. if (blockCompilation === void 0) { blockCompilation = false; }
  78854. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  78855. _this.blurSteps = blurSteps;
  78856. _this.onApplyObservable.add(function (effect) {
  78857. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  78858. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  78859. blurSteps.forEach(function (step, index) {
  78860. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  78861. });
  78862. });
  78863. if (!blockCompilation) {
  78864. _this.updateEffect();
  78865. }
  78866. return _this;
  78867. }
  78868. /**
  78869. * Updates the effect with the current post process compile time values and recompiles the shader.
  78870. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78871. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78872. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78873. * @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
  78874. * @param onCompiled Called when the shader has been compiled.
  78875. * @param onError Called if there is an error when compiling a shader.
  78876. */
  78877. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78878. if (defines === void 0) { defines = null; }
  78879. if (uniforms === void 0) { uniforms = null; }
  78880. if (samplers === void 0) { samplers = null; }
  78881. if (!defines) {
  78882. defines = "";
  78883. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  78884. }
  78885. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  78886. };
  78887. return DepthOfFieldMergePostProcess;
  78888. }(BABYLON.PostProcess));
  78889. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  78890. })(BABYLON || (BABYLON = {}));
  78891. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  78892. var BABYLON;
  78893. (function (BABYLON) {
  78894. /**
  78895. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  78896. */
  78897. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  78898. __extends(CircleOfConfusionPostProcess, _super);
  78899. /**
  78900. * Creates a new instance CircleOfConfusionPostProcess
  78901. * @param name The name of the effect.
  78902. * @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.
  78903. * @param options The required width/height ratio to downsize to before computing the render pass.
  78904. * @param camera The camera to apply the render pass to.
  78905. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78906. * @param engine The engine which the post process will be applied. (default: current engine)
  78907. * @param reusable If the post process can be reused on the same frame. (default: false)
  78908. * @param textureType Type of textures used when performing the post process. (default: 0)
  78909. * @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)
  78910. */
  78911. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78912. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78913. if (blockCompilation === void 0) { blockCompilation = false; }
  78914. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78915. /**
  78916. * 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.
  78917. */
  78918. _this.lensSize = 50;
  78919. /**
  78920. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  78921. */
  78922. _this.fStop = 1.4;
  78923. /**
  78924. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  78925. */
  78926. _this.focusDistance = 2000;
  78927. /**
  78928. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  78929. */
  78930. _this.focalLength = 50;
  78931. _this._depthTexture = null;
  78932. _this._depthTexture = depthTexture;
  78933. _this.onApplyObservable.add(function (effect) {
  78934. if (!_this._depthTexture) {
  78935. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  78936. return;
  78937. }
  78938. effect.setTexture("depthSampler", _this._depthTexture);
  78939. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  78940. var aperture = _this.lensSize / _this.fStop;
  78941. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  78942. effect.setFloat('focusDistance', _this.focusDistance);
  78943. effect.setFloat('cocPrecalculation', cocPrecalculation);
  78944. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  78945. });
  78946. return _this;
  78947. }
  78948. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  78949. /**
  78950. * 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.
  78951. */
  78952. set: function (value) {
  78953. this._depthTexture = value;
  78954. },
  78955. enumerable: true,
  78956. configurable: true
  78957. });
  78958. return CircleOfConfusionPostProcess;
  78959. }(BABYLON.PostProcess));
  78960. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  78961. })(BABYLON || (BABYLON = {}));
  78962. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  78963. var BABYLON;
  78964. (function (BABYLON) {
  78965. /**
  78966. * Specifies the level of max blur that should be applied when using the depth of field effect
  78967. */
  78968. var DepthOfFieldEffectBlurLevel;
  78969. (function (DepthOfFieldEffectBlurLevel) {
  78970. /**
  78971. * Subtle blur
  78972. */
  78973. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  78974. /**
  78975. * Medium blur
  78976. */
  78977. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  78978. /**
  78979. * Large blur
  78980. */
  78981. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  78982. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  78983. ;
  78984. /**
  78985. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  78986. */
  78987. var DepthOfFieldEffect = /** @class */ (function (_super) {
  78988. __extends(DepthOfFieldEffect, _super);
  78989. /**
  78990. * Creates a new instance DepthOfFieldEffect
  78991. * @param scene The scene the effect belongs to.
  78992. * @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.
  78993. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78994. * @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)
  78995. */
  78996. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  78997. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  78998. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78999. if (blockCompilation === void 0) { blockCompilation = false; }
  79000. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79001. return _this._effects;
  79002. }, true) || this;
  79003. /**
  79004. * @hidden Internal post processes in depth of field effect
  79005. */
  79006. _this._effects = [];
  79007. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79008. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79009. // 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)
  79010. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79011. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79012. _this._depthOfFieldBlurY = [];
  79013. _this._depthOfFieldBlurX = [];
  79014. var blurCount = 1;
  79015. var kernelSize = 15;
  79016. switch (blurLevel) {
  79017. case DepthOfFieldEffectBlurLevel.High: {
  79018. blurCount = 3;
  79019. kernelSize = 51;
  79020. break;
  79021. }
  79022. case DepthOfFieldEffectBlurLevel.Medium: {
  79023. blurCount = 2;
  79024. kernelSize = 31;
  79025. break;
  79026. }
  79027. default: {
  79028. kernelSize = 15;
  79029. blurCount = 1;
  79030. break;
  79031. }
  79032. }
  79033. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79034. var ratio = 1.0;
  79035. for (var i = 0; i < blurCount; i++) {
  79036. 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);
  79037. blurY.autoClear = false;
  79038. ratio = 0.75 / Math.pow(2, i);
  79039. 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);
  79040. blurX.autoClear = false;
  79041. _this._depthOfFieldBlurY.push(blurY);
  79042. _this._depthOfFieldBlurX.push(blurX);
  79043. }
  79044. // Set all post processes on the effect.
  79045. _this._effects = [_this._circleOfConfusion];
  79046. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79047. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79048. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79049. }
  79050. // Merge blurred images with original image based on circleOfConfusion
  79051. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79052. _this._dofMerge.autoClear = false;
  79053. _this._effects.push(_this._dofMerge);
  79054. return _this;
  79055. }
  79056. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79057. get: function () {
  79058. return this._circleOfConfusion.focalLength;
  79059. },
  79060. /**
  79061. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79062. */
  79063. set: function (value) {
  79064. this._circleOfConfusion.focalLength = value;
  79065. },
  79066. enumerable: true,
  79067. configurable: true
  79068. });
  79069. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79070. get: function () {
  79071. return this._circleOfConfusion.fStop;
  79072. },
  79073. /**
  79074. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79075. */
  79076. set: function (value) {
  79077. this._circleOfConfusion.fStop = value;
  79078. },
  79079. enumerable: true,
  79080. configurable: true
  79081. });
  79082. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79083. get: function () {
  79084. return this._circleOfConfusion.focusDistance;
  79085. },
  79086. /**
  79087. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79088. */
  79089. set: function (value) {
  79090. this._circleOfConfusion.focusDistance = value;
  79091. },
  79092. enumerable: true,
  79093. configurable: true
  79094. });
  79095. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  79096. get: function () {
  79097. return this._circleOfConfusion.lensSize;
  79098. },
  79099. /**
  79100. * 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.
  79101. */
  79102. set: function (value) {
  79103. this._circleOfConfusion.lensSize = value;
  79104. },
  79105. enumerable: true,
  79106. configurable: true
  79107. });
  79108. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  79109. /**
  79110. * 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.
  79111. */
  79112. set: function (value) {
  79113. this._circleOfConfusion.depthTexture = value;
  79114. },
  79115. enumerable: true,
  79116. configurable: true
  79117. });
  79118. /**
  79119. * Disposes each of the internal effects for a given camera.
  79120. * @param camera The camera to dispose the effect on.
  79121. */
  79122. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  79123. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79124. this._effects[effectIndex].dispose(camera);
  79125. }
  79126. };
  79127. /**
  79128. * @hidden Internal
  79129. */
  79130. DepthOfFieldEffect.prototype._updateEffects = function () {
  79131. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79132. this._effects[effectIndex].updateEffect();
  79133. }
  79134. };
  79135. /**
  79136. * Internal
  79137. * @returns if all the contained post processes are ready.
  79138. * @hidden
  79139. */
  79140. DepthOfFieldEffect.prototype._isReady = function () {
  79141. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79142. if (!this._effects[effectIndex].isReady()) {
  79143. return false;
  79144. }
  79145. }
  79146. return true;
  79147. };
  79148. return DepthOfFieldEffect;
  79149. }(BABYLON.PostProcessRenderEffect));
  79150. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  79151. })(BABYLON || (BABYLON = {}));
  79152. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  79153. var BABYLON;
  79154. (function (BABYLON) {
  79155. /**
  79156. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79157. */
  79158. var BloomMergePostProcess = /** @class */ (function (_super) {
  79159. __extends(BloomMergePostProcess, _super);
  79160. /**
  79161. * Creates a new instance of @see BloomMergePostProcess
  79162. * @param name The name of the effect.
  79163. * @param originalFromInput Post process which's input will be used for the merge.
  79164. * @param blurred Blurred highlights post process which's output will be used.
  79165. * @param weight Weight of the bloom to be added to the original input.
  79166. * @param options The required width/height ratio to downsize to before computing the render pass.
  79167. * @param camera The camera to apply the render pass to.
  79168. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79169. * @param engine The engine which the post process will be applied. (default: current engine)
  79170. * @param reusable If the post process can be reused on the same frame. (default: false)
  79171. * @param textureType Type of textures used when performing the post process. (default: 0)
  79172. * @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)
  79173. */
  79174. function BloomMergePostProcess(name, originalFromInput, blurred,
  79175. /** Weight of the bloom to be added to the original input. */
  79176. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79177. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79178. if (blockCompilation === void 0) { blockCompilation = false; }
  79179. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79180. _this.weight = weight;
  79181. _this.onApplyObservable.add(function (effect) {
  79182. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79183. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  79184. effect.setFloat("bloomWeight", _this.weight);
  79185. });
  79186. if (!blockCompilation) {
  79187. _this.updateEffect();
  79188. }
  79189. return _this;
  79190. }
  79191. return BloomMergePostProcess;
  79192. }(BABYLON.PostProcess));
  79193. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  79194. })(BABYLON || (BABYLON = {}));
  79195. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  79196. var BABYLON;
  79197. (function (BABYLON) {
  79198. /**
  79199. * 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.
  79200. */
  79201. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  79202. __extends(ExtractHighlightsPostProcess, _super);
  79203. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79204. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79205. if (blockCompilation === void 0) { blockCompilation = false; }
  79206. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79207. /**
  79208. * The luminance threshold, pixels below this value will be set to black.
  79209. */
  79210. _this.threshold = 0.9;
  79211. /** @hidden */
  79212. _this._exposure = 1;
  79213. /**
  79214. * Post process which has the input texture to be used when performing highlight extraction
  79215. * @hidden
  79216. */
  79217. _this._inputPostProcess = null;
  79218. _this.onApplyObservable.add(function (effect) {
  79219. if (_this._inputPostProcess) {
  79220. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  79221. }
  79222. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  79223. effect.setFloat('exposure', _this._exposure);
  79224. });
  79225. return _this;
  79226. }
  79227. return ExtractHighlightsPostProcess;
  79228. }(BABYLON.PostProcess));
  79229. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  79230. })(BABYLON || (BABYLON = {}));
  79231. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  79232. var BABYLON;
  79233. (function (BABYLON) {
  79234. /**
  79235. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  79236. */
  79237. var BloomEffect = /** @class */ (function (_super) {
  79238. __extends(BloomEffect, _super);
  79239. /**
  79240. * Creates a new instance of @see BloomEffect
  79241. * @param scene The scene the effect belongs to.
  79242. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  79243. * @param bloomKernel The size of the kernel to be used when applying the blur.
  79244. * @param bloomWeight The the strength of bloom.
  79245. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79246. * @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)
  79247. */
  79248. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  79249. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79250. if (blockCompilation === void 0) { blockCompilation = false; }
  79251. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  79252. return _this._effects;
  79253. }, true) || this;
  79254. _this.bloomScale = bloomScale;
  79255. /**
  79256. * @hidden Internal
  79257. */
  79258. _this._effects = [];
  79259. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79260. _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);
  79261. _this._blurX.alwaysForcePOT = true;
  79262. _this._blurX.autoClear = false;
  79263. _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);
  79264. _this._blurY.alwaysForcePOT = true;
  79265. _this._blurY.autoClear = false;
  79266. _this.kernel = bloomKernel;
  79267. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  79268. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79269. _this._merge.autoClear = false;
  79270. _this._effects.push(_this._merge);
  79271. return _this;
  79272. }
  79273. Object.defineProperty(BloomEffect.prototype, "threshold", {
  79274. /**
  79275. * The luminance threshold to find bright areas of the image to bloom.
  79276. */
  79277. get: function () {
  79278. return this._downscale.threshold;
  79279. },
  79280. set: function (value) {
  79281. this._downscale.threshold = value;
  79282. },
  79283. enumerable: true,
  79284. configurable: true
  79285. });
  79286. Object.defineProperty(BloomEffect.prototype, "weight", {
  79287. /**
  79288. * The strength of the bloom.
  79289. */
  79290. get: function () {
  79291. return this._merge.weight;
  79292. },
  79293. set: function (value) {
  79294. this._merge.weight = value;
  79295. },
  79296. enumerable: true,
  79297. configurable: true
  79298. });
  79299. Object.defineProperty(BloomEffect.prototype, "kernel", {
  79300. /**
  79301. * Specifies the size of the bloom blur kernel, relative to the final output size
  79302. */
  79303. get: function () {
  79304. return this._blurX.kernel / this.bloomScale;
  79305. },
  79306. set: function (value) {
  79307. this._blurX.kernel = value * this.bloomScale;
  79308. this._blurY.kernel = value * this.bloomScale;
  79309. },
  79310. enumerable: true,
  79311. configurable: true
  79312. });
  79313. /**
  79314. * Disposes each of the internal effects for a given camera.
  79315. * @param camera The camera to dispose the effect on.
  79316. */
  79317. BloomEffect.prototype.disposeEffects = function (camera) {
  79318. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79319. this._effects[effectIndex].dispose(camera);
  79320. }
  79321. };
  79322. /**
  79323. * @hidden Internal
  79324. */
  79325. BloomEffect.prototype._updateEffects = function () {
  79326. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79327. this._effects[effectIndex].updateEffect();
  79328. }
  79329. };
  79330. /**
  79331. * Internal
  79332. * @returns if all the contained post processes are ready.
  79333. * @hidden
  79334. */
  79335. BloomEffect.prototype._isReady = function () {
  79336. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79337. if (!this._effects[effectIndex].isReady()) {
  79338. return false;
  79339. }
  79340. }
  79341. return true;
  79342. };
  79343. return BloomEffect;
  79344. }(BABYLON.PostProcessRenderEffect));
  79345. BABYLON.BloomEffect = BloomEffect;
  79346. })(BABYLON || (BABYLON = {}));
  79347. //# sourceMappingURL=babylon.bloomEffect.js.map
  79348. var BABYLON;
  79349. (function (BABYLON) {
  79350. /**
  79351. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  79352. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  79353. */
  79354. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  79355. __extends(DefaultRenderingPipeline, _super);
  79356. /**
  79357. * @constructor
  79358. * @param {string} name - The rendering pipeline name (default: "")
  79359. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  79360. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  79361. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  79362. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  79363. */
  79364. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  79365. if (name === void 0) { name = ""; }
  79366. if (hdr === void 0) { hdr = true; }
  79367. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79368. if (automaticBuild === void 0) { automaticBuild = true; }
  79369. var _this = _super.call(this, scene.getEngine(), name) || this;
  79370. _this._camerasToBeAttached = [];
  79371. /**
  79372. * ID of the sharpen post process,
  79373. */
  79374. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  79375. /**
  79376. * ID of the image processing post process;
  79377. */
  79378. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  79379. /**
  79380. * ID of the Fast Approximate Anti-Aliasing post process;
  79381. */
  79382. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  79383. /**
  79384. * ID of the chromatic aberration post process,
  79385. */
  79386. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  79387. /**
  79388. * ID of the grain post process
  79389. */
  79390. _this.GrainPostProcessId = "GrainPostProcessEffect";
  79391. /**
  79392. * Glow post process which adds a glow to emmisive areas of the image
  79393. */
  79394. _this._glowLayer = null;
  79395. /**
  79396. * Animations which can be used to tweak settings over a period of time
  79397. */
  79398. _this.animations = [];
  79399. _this._imageProcessingConfigurationObserver = null;
  79400. // Values
  79401. _this._sharpenEnabled = false;
  79402. _this._bloomEnabled = false;
  79403. _this._depthOfFieldEnabled = false;
  79404. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  79405. _this._fxaaEnabled = false;
  79406. _this._imageProcessingEnabled = true;
  79407. _this._bloomScale = 0.5;
  79408. _this._chromaticAberrationEnabled = false;
  79409. _this._grainEnabled = false;
  79410. _this._buildAllowed = true;
  79411. _this._resizeObserver = null;
  79412. _this._hardwareScaleLevel = 1.0;
  79413. _this._bloomKernel = 64;
  79414. /**
  79415. * Specifies the weight of the bloom in the final rendering
  79416. */
  79417. _this._bloomWeight = 0.15;
  79418. /**
  79419. * Specifies the luma threshold for the area that will be blurred by the bloom
  79420. */
  79421. _this._bloomThreshold = 0.9;
  79422. _this._samples = 1;
  79423. _this._hasCleared = false;
  79424. _this._prevPostProcess = null;
  79425. _this._prevPrevPostProcess = null;
  79426. _this._cameras = cameras || scene.cameras;
  79427. _this._cameras = _this._cameras.slice();
  79428. _this._camerasToBeAttached = _this._cameras.slice();
  79429. _this._buildAllowed = automaticBuild;
  79430. // Initialize
  79431. _this._scene = scene;
  79432. var caps = _this._scene.getEngine().getCaps();
  79433. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  79434. // Misc
  79435. if (_this._hdr) {
  79436. if (caps.textureHalfFloatRender) {
  79437. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79438. }
  79439. else if (caps.textureFloatRender) {
  79440. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79441. }
  79442. }
  79443. else {
  79444. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79445. }
  79446. // Attach
  79447. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79448. var engine = _this._scene.getEngine();
  79449. // Create post processes before hand so they can be modified before enabled.
  79450. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  79451. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79452. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  79453. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  79454. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  79455. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79456. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  79457. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79458. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  79459. _this._resizeObserver = engine.onResizeObservable.add(function () {
  79460. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  79461. _this.bloomKernel = _this.bloomKernel;
  79462. });
  79463. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  79464. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  79465. });
  79466. _this._buildPipeline();
  79467. return _this;
  79468. }
  79469. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  79470. get: function () {
  79471. return this._sharpenEnabled;
  79472. },
  79473. /**
  79474. * Enable or disable the sharpen process from the pipeline
  79475. */
  79476. set: function (enabled) {
  79477. if (this._sharpenEnabled === enabled) {
  79478. return;
  79479. }
  79480. this._sharpenEnabled = enabled;
  79481. this._buildPipeline();
  79482. },
  79483. enumerable: true,
  79484. configurable: true
  79485. });
  79486. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  79487. /**
  79488. * Specifies the size of the bloom blur kernel, relative to the final output size
  79489. */
  79490. get: function () {
  79491. return this._bloomKernel;
  79492. },
  79493. set: function (value) {
  79494. this._bloomKernel = value;
  79495. this.bloom.kernel = value / this._hardwareScaleLevel;
  79496. },
  79497. enumerable: true,
  79498. configurable: true
  79499. });
  79500. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79501. get: function () {
  79502. return this._bloomWeight;
  79503. },
  79504. /**
  79505. * The strength of the bloom.
  79506. */
  79507. set: function (value) {
  79508. if (this._bloomWeight === value) {
  79509. return;
  79510. }
  79511. this.bloom.weight = value;
  79512. this._bloomWeight = value;
  79513. },
  79514. enumerable: true,
  79515. configurable: true
  79516. });
  79517. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  79518. get: function () {
  79519. return this._bloomThreshold;
  79520. },
  79521. /**
  79522. * The strength of the bloom.
  79523. */
  79524. set: function (value) {
  79525. if (this._bloomThreshold === value) {
  79526. return;
  79527. }
  79528. this.bloom.threshold = value;
  79529. this._bloomThreshold = value;
  79530. },
  79531. enumerable: true,
  79532. configurable: true
  79533. });
  79534. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  79535. get: function () {
  79536. return this._bloomScale;
  79537. },
  79538. /**
  79539. * The scale of the bloom, lower value will provide better performance.
  79540. */
  79541. set: function (value) {
  79542. if (this._bloomScale === value) {
  79543. return;
  79544. }
  79545. this._bloomScale = value;
  79546. // recreate bloom and dispose old as this setting is not dynamic
  79547. this._rebuildBloom();
  79548. this._buildPipeline();
  79549. },
  79550. enumerable: true,
  79551. configurable: true
  79552. });
  79553. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  79554. get: function () {
  79555. return this._bloomEnabled;
  79556. },
  79557. /**
  79558. * Enable or disable the bloom from the pipeline
  79559. */
  79560. set: function (enabled) {
  79561. if (this._bloomEnabled === enabled) {
  79562. return;
  79563. }
  79564. this._bloomEnabled = enabled;
  79565. this._buildPipeline();
  79566. },
  79567. enumerable: true,
  79568. configurable: true
  79569. });
  79570. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  79571. // recreate bloom and dispose old as this setting is not dynamic
  79572. var oldBloom = this.bloom;
  79573. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  79574. this.bloom.threshold = oldBloom.threshold;
  79575. for (var i = 0; i < this._cameras.length; i++) {
  79576. oldBloom.disposeEffects(this._cameras[i]);
  79577. }
  79578. };
  79579. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  79580. /**
  79581. * If the depth of field is enabled.
  79582. */
  79583. get: function () {
  79584. return this._depthOfFieldEnabled;
  79585. },
  79586. set: function (enabled) {
  79587. if (this._depthOfFieldEnabled === enabled) {
  79588. return;
  79589. }
  79590. this._depthOfFieldEnabled = enabled;
  79591. this._buildPipeline();
  79592. },
  79593. enumerable: true,
  79594. configurable: true
  79595. });
  79596. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  79597. /**
  79598. * Blur level of the depth of field effect. (Higher blur will effect performance)
  79599. */
  79600. get: function () {
  79601. return this._depthOfFieldBlurLevel;
  79602. },
  79603. set: function (value) {
  79604. if (this._depthOfFieldBlurLevel === value) {
  79605. return;
  79606. }
  79607. this._depthOfFieldBlurLevel = value;
  79608. // recreate dof and dispose old as this setting is not dynamic
  79609. var oldDof = this.depthOfField;
  79610. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  79611. this.depthOfField.focalLength = oldDof.focalLength;
  79612. this.depthOfField.focusDistance = oldDof.focusDistance;
  79613. this.depthOfField.fStop = oldDof.fStop;
  79614. this.depthOfField.lensSize = oldDof.lensSize;
  79615. for (var i = 0; i < this._cameras.length; i++) {
  79616. oldDof.disposeEffects(this._cameras[i]);
  79617. }
  79618. this._buildPipeline();
  79619. },
  79620. enumerable: true,
  79621. configurable: true
  79622. });
  79623. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  79624. get: function () {
  79625. return this._fxaaEnabled;
  79626. },
  79627. /**
  79628. * If the anti aliasing is enabled.
  79629. */
  79630. set: function (enabled) {
  79631. if (this._fxaaEnabled === enabled) {
  79632. return;
  79633. }
  79634. this._fxaaEnabled = enabled;
  79635. this._buildPipeline();
  79636. },
  79637. enumerable: true,
  79638. configurable: true
  79639. });
  79640. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  79641. get: function () {
  79642. return this._samples;
  79643. },
  79644. /**
  79645. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79646. */
  79647. set: function (sampleCount) {
  79648. if (this._samples === sampleCount) {
  79649. return;
  79650. }
  79651. this._samples = sampleCount;
  79652. this._buildPipeline();
  79653. },
  79654. enumerable: true,
  79655. configurable: true
  79656. });
  79657. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  79658. get: function () {
  79659. return this._imageProcessingEnabled;
  79660. },
  79661. /**
  79662. * If image processing is enabled.
  79663. */
  79664. set: function (enabled) {
  79665. if (this._imageProcessingEnabled === enabled) {
  79666. return;
  79667. }
  79668. this._imageProcessingEnabled = enabled;
  79669. this._buildPipeline();
  79670. },
  79671. enumerable: true,
  79672. configurable: true
  79673. });
  79674. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  79675. get: function () {
  79676. return this._glowLayer == null;
  79677. },
  79678. /**
  79679. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  79680. */
  79681. set: function (enabled) {
  79682. if (enabled && !this._glowLayer) {
  79683. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  79684. }
  79685. else if (!enabled && this._glowLayer) {
  79686. this._glowLayer.dispose();
  79687. this._glowLayer = null;
  79688. }
  79689. },
  79690. enumerable: true,
  79691. configurable: true
  79692. });
  79693. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  79694. get: function () {
  79695. return this._chromaticAberrationEnabled;
  79696. },
  79697. /**
  79698. * Enable or disable the chromaticAberration process from the pipeline
  79699. */
  79700. set: function (enabled) {
  79701. if (this._chromaticAberrationEnabled === enabled) {
  79702. return;
  79703. }
  79704. this._chromaticAberrationEnabled = enabled;
  79705. this._buildPipeline();
  79706. },
  79707. enumerable: true,
  79708. configurable: true
  79709. });
  79710. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  79711. get: function () {
  79712. return this._grainEnabled;
  79713. },
  79714. /**
  79715. * Enable or disable the grain process from the pipeline
  79716. */
  79717. set: function (enabled) {
  79718. if (this._grainEnabled === enabled) {
  79719. return;
  79720. }
  79721. this._grainEnabled = enabled;
  79722. this._buildPipeline();
  79723. },
  79724. enumerable: true,
  79725. configurable: true
  79726. });
  79727. /**
  79728. * Force the compilation of the entire pipeline.
  79729. */
  79730. DefaultRenderingPipeline.prototype.prepare = function () {
  79731. var previousState = this._buildAllowed;
  79732. this._buildAllowed = true;
  79733. this._buildPipeline();
  79734. this._buildAllowed = previousState;
  79735. };
  79736. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  79737. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  79738. if (this._hasCleared) {
  79739. postProcess.autoClear = false;
  79740. }
  79741. else {
  79742. postProcess.autoClear = true;
  79743. this._scene.autoClear = false;
  79744. this._hasCleared = true;
  79745. }
  79746. if (!skipTextureSharing) {
  79747. if (this._prevPrevPostProcess) {
  79748. postProcess.shareOutputWith(this._prevPrevPostProcess);
  79749. }
  79750. else {
  79751. postProcess.useOwnOutput();
  79752. }
  79753. if (this._prevPostProcess) {
  79754. this._prevPrevPostProcess = this._prevPostProcess;
  79755. }
  79756. this._prevPostProcess = postProcess;
  79757. }
  79758. };
  79759. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  79760. var _this = this;
  79761. if (!this._buildAllowed) {
  79762. return;
  79763. }
  79764. this._scene.autoClear = true;
  79765. var engine = this._scene.getEngine();
  79766. this._disposePostProcesses();
  79767. if (this._cameras !== null) {
  79768. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79769. // get back cameras to be used to reattach pipeline
  79770. this._cameras = this._camerasToBeAttached.slice();
  79771. }
  79772. this._reset();
  79773. this._prevPostProcess = null;
  79774. this._prevPrevPostProcess = null;
  79775. this._hasCleared = false;
  79776. if (this.depthOfFieldEnabled) {
  79777. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  79778. this.depthOfField.depthTexture = depthTexture;
  79779. if (!this.depthOfField._isReady()) {
  79780. this.depthOfField._updateEffects();
  79781. }
  79782. this.addEffect(this.depthOfField);
  79783. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  79784. }
  79785. if (this.bloomEnabled) {
  79786. if (!this.bloom._isReady()) {
  79787. this.bloom._updateEffects();
  79788. }
  79789. this.addEffect(this.bloom);
  79790. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  79791. }
  79792. if (this._imageProcessingEnabled) {
  79793. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  79794. if (this._hdr) {
  79795. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  79796. this._setAutoClearAndTextureSharing(this.imageProcessing);
  79797. }
  79798. else {
  79799. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  79800. }
  79801. }
  79802. if (this.sharpenEnabled) {
  79803. if (!this.sharpen.isReady()) {
  79804. this.sharpen.updateEffect();
  79805. }
  79806. this.addEffect(this._sharpenEffect);
  79807. this._setAutoClearAndTextureSharing(this.sharpen);
  79808. }
  79809. if (this.grainEnabled) {
  79810. if (!this.grain.isReady()) {
  79811. this.grain.updateEffect();
  79812. }
  79813. this.addEffect(this._grainEffect);
  79814. this._setAutoClearAndTextureSharing(this.grain);
  79815. }
  79816. if (this.chromaticAberrationEnabled) {
  79817. if (!this.chromaticAberration.isReady()) {
  79818. this.chromaticAberration.updateEffect();
  79819. }
  79820. this.addEffect(this._chromaticAberrationEffect);
  79821. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  79822. }
  79823. if (this.fxaaEnabled) {
  79824. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  79825. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  79826. this._setAutoClearAndTextureSharing(this.fxaa, true);
  79827. }
  79828. if (this._cameras !== null) {
  79829. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79830. }
  79831. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  79832. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79833. }
  79834. };
  79835. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  79836. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  79837. for (var i = 0; i < this._cameras.length; i++) {
  79838. var camera = this._cameras[i];
  79839. if (this.imageProcessing) {
  79840. this.imageProcessing.dispose(camera);
  79841. }
  79842. if (this.fxaa) {
  79843. this.fxaa.dispose(camera);
  79844. }
  79845. // These are created in the constructor and should not be disposed on every pipeline change
  79846. if (disposeNonRecreated) {
  79847. if (this.sharpen) {
  79848. this.sharpen.dispose(camera);
  79849. }
  79850. if (this.depthOfField) {
  79851. this.depthOfField.disposeEffects(camera);
  79852. }
  79853. if (this.bloom) {
  79854. this.bloom.disposeEffects(camera);
  79855. }
  79856. if (this.chromaticAberration) {
  79857. this.chromaticAberration.dispose(camera);
  79858. }
  79859. if (this.grain) {
  79860. this.grain.dispose(camera);
  79861. }
  79862. if (this._glowLayer) {
  79863. this._glowLayer.dispose();
  79864. }
  79865. }
  79866. }
  79867. this.imageProcessing = null;
  79868. this.fxaa = null;
  79869. if (disposeNonRecreated) {
  79870. this.sharpen = null;
  79871. this._sharpenEffect = null;
  79872. this.depthOfField = null;
  79873. this.bloom = null;
  79874. this.chromaticAberration = null;
  79875. this._chromaticAberrationEffect = null;
  79876. this.grain = null;
  79877. this._grainEffect = null;
  79878. this._glowLayer = null;
  79879. }
  79880. };
  79881. /**
  79882. * Adds a camera to the pipeline
  79883. * @param camera the camera to be added
  79884. */
  79885. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  79886. this._camerasToBeAttached.push(camera);
  79887. this._buildPipeline();
  79888. };
  79889. /**
  79890. * Removes a camera from the pipeline
  79891. * @param camera the camera to remove
  79892. */
  79893. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  79894. var index = this._camerasToBeAttached.indexOf(camera);
  79895. this._camerasToBeAttached.splice(index, 1);
  79896. this._buildPipeline();
  79897. };
  79898. /**
  79899. * Dispose of the pipeline and stop all post processes
  79900. */
  79901. DefaultRenderingPipeline.prototype.dispose = function () {
  79902. this._disposePostProcesses(true);
  79903. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79904. this._scene.autoClear = true;
  79905. if (this._resizeObserver) {
  79906. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  79907. this._resizeObserver = null;
  79908. }
  79909. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  79910. _super.prototype.dispose.call(this);
  79911. };
  79912. /**
  79913. * Serialize the rendering pipeline (Used when exporting)
  79914. * @returns the serialized object
  79915. */
  79916. DefaultRenderingPipeline.prototype.serialize = function () {
  79917. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79918. serializationObject.customType = "DefaultRenderingPipeline";
  79919. return serializationObject;
  79920. };
  79921. /**
  79922. * Parse the serialized pipeline
  79923. * @param source Source pipeline.
  79924. * @param scene The scene to load the pipeline to.
  79925. * @param rootUrl The URL of the serialized pipeline.
  79926. * @returns An instantiated pipeline from the serialized object.
  79927. */
  79928. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79929. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  79930. };
  79931. __decorate([
  79932. BABYLON.serialize()
  79933. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  79934. __decorate([
  79935. BABYLON.serialize()
  79936. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  79937. __decorate([
  79938. BABYLON.serialize()
  79939. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  79940. __decorate([
  79941. BABYLON.serialize()
  79942. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  79943. __decorate([
  79944. BABYLON.serialize()
  79945. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  79946. __decorate([
  79947. BABYLON.serialize()
  79948. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  79949. __decorate([
  79950. BABYLON.serialize()
  79951. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  79952. __decorate([
  79953. BABYLON.serialize()
  79954. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  79955. __decorate([
  79956. BABYLON.serialize()
  79957. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  79958. __decorate([
  79959. BABYLON.serialize()
  79960. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  79961. __decorate([
  79962. BABYLON.serialize()
  79963. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  79964. __decorate([
  79965. BABYLON.serialize()
  79966. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  79967. __decorate([
  79968. BABYLON.serialize()
  79969. ], DefaultRenderingPipeline.prototype, "samples", null);
  79970. __decorate([
  79971. BABYLON.serialize()
  79972. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  79973. __decorate([
  79974. BABYLON.serialize()
  79975. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  79976. __decorate([
  79977. BABYLON.serialize()
  79978. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  79979. __decorate([
  79980. BABYLON.serialize()
  79981. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  79982. return DefaultRenderingPipeline;
  79983. }(BABYLON.PostProcessRenderPipeline));
  79984. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  79985. })(BABYLON || (BABYLON = {}));
  79986. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  79987. var BABYLON;
  79988. (function (BABYLON) {
  79989. /**
  79990. * @hidden
  79991. */
  79992. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  79993. __extends(ImageProcessingConfigurationDefines, _super);
  79994. function ImageProcessingConfigurationDefines() {
  79995. var _this = _super.call(this) || this;
  79996. _this.IMAGEPROCESSING = false;
  79997. _this.VIGNETTE = false;
  79998. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  79999. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80000. _this.TONEMAPPING = false;
  80001. _this.TONEMAPPING_ACES = false;
  80002. _this.CONTRAST = false;
  80003. _this.COLORCURVES = false;
  80004. _this.COLORGRADING = false;
  80005. _this.COLORGRADING3D = false;
  80006. _this.SAMPLER3DGREENDEPTH = false;
  80007. _this.SAMPLER3DBGRMAP = false;
  80008. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80009. _this.EXPOSURE = false;
  80010. _this.rebuild();
  80011. return _this;
  80012. }
  80013. return ImageProcessingConfigurationDefines;
  80014. }(BABYLON.MaterialDefines));
  80015. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80016. /**
  80017. * This groups together the common properties used for image processing either in direct forward pass
  80018. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80019. * or not.
  80020. */
  80021. var ImageProcessingConfiguration = /** @class */ (function () {
  80022. function ImageProcessingConfiguration() {
  80023. /**
  80024. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80025. */
  80026. this.colorCurves = new BABYLON.ColorCurves();
  80027. this._colorCurvesEnabled = false;
  80028. this._colorGradingEnabled = false;
  80029. this._colorGradingWithGreenDepth = true;
  80030. this._colorGradingBGR = true;
  80031. /** @hidden */
  80032. this._exposure = 1.0;
  80033. this._toneMappingEnabled = false;
  80034. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80035. this._contrast = 1.0;
  80036. /**
  80037. * Vignette stretch size.
  80038. */
  80039. this.vignetteStretch = 0;
  80040. /**
  80041. * Vignette centre X Offset.
  80042. */
  80043. this.vignetteCentreX = 0;
  80044. /**
  80045. * Vignette centre Y Offset.
  80046. */
  80047. this.vignetteCentreY = 0;
  80048. /**
  80049. * Vignette weight or intensity of the vignette effect.
  80050. */
  80051. this.vignetteWeight = 1.5;
  80052. /**
  80053. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80054. * if vignetteEnabled is set to true.
  80055. */
  80056. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80057. /**
  80058. * Camera field of view used by the Vignette effect.
  80059. */
  80060. this.vignetteCameraFov = 0.5;
  80061. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80062. this._vignetteEnabled = false;
  80063. this._applyByPostProcess = false;
  80064. this._isEnabled = true;
  80065. /**
  80066. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80067. */
  80068. this.onUpdateParameters = new BABYLON.Observable();
  80069. }
  80070. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80071. /**
  80072. * Gets wether the color curves effect is enabled.
  80073. */
  80074. get: function () {
  80075. return this._colorCurvesEnabled;
  80076. },
  80077. /**
  80078. * Sets wether the color curves effect is enabled.
  80079. */
  80080. set: function (value) {
  80081. if (this._colorCurvesEnabled === value) {
  80082. return;
  80083. }
  80084. this._colorCurvesEnabled = value;
  80085. this._updateParameters();
  80086. },
  80087. enumerable: true,
  80088. configurable: true
  80089. });
  80090. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  80091. /**
  80092. * Gets wether the color grading effect is enabled.
  80093. */
  80094. get: function () {
  80095. return this._colorGradingEnabled;
  80096. },
  80097. /**
  80098. * Sets wether the color grading effect is enabled.
  80099. */
  80100. set: function (value) {
  80101. if (this._colorGradingEnabled === value) {
  80102. return;
  80103. }
  80104. this._colorGradingEnabled = value;
  80105. this._updateParameters();
  80106. },
  80107. enumerable: true,
  80108. configurable: true
  80109. });
  80110. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  80111. /**
  80112. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  80113. */
  80114. get: function () {
  80115. return this._colorGradingWithGreenDepth;
  80116. },
  80117. /**
  80118. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  80119. */
  80120. set: function (value) {
  80121. if (this._colorGradingWithGreenDepth === value) {
  80122. return;
  80123. }
  80124. this._colorGradingWithGreenDepth = value;
  80125. this._updateParameters();
  80126. },
  80127. enumerable: true,
  80128. configurable: true
  80129. });
  80130. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  80131. /**
  80132. * Gets wether the color grading texture contains BGR values.
  80133. */
  80134. get: function () {
  80135. return this._colorGradingBGR;
  80136. },
  80137. /**
  80138. * Sets wether the color grading texture contains BGR values.
  80139. */
  80140. set: function (value) {
  80141. if (this._colorGradingBGR === value) {
  80142. return;
  80143. }
  80144. this._colorGradingBGR = value;
  80145. this._updateParameters();
  80146. },
  80147. enumerable: true,
  80148. configurable: true
  80149. });
  80150. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  80151. /**
  80152. * Gets the Exposure used in the effect.
  80153. */
  80154. get: function () {
  80155. return this._exposure;
  80156. },
  80157. /**
  80158. * Sets the Exposure used in the effect.
  80159. */
  80160. set: function (value) {
  80161. if (this._exposure === value) {
  80162. return;
  80163. }
  80164. this._exposure = value;
  80165. this._updateParameters();
  80166. },
  80167. enumerable: true,
  80168. configurable: true
  80169. });
  80170. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  80171. /**
  80172. * Gets wether the tone mapping effect is enabled.
  80173. */
  80174. get: function () {
  80175. return this._toneMappingEnabled;
  80176. },
  80177. /**
  80178. * Sets wether the tone mapping effect is enabled.
  80179. */
  80180. set: function (value) {
  80181. if (this._toneMappingEnabled === value) {
  80182. return;
  80183. }
  80184. this._toneMappingEnabled = value;
  80185. this._updateParameters();
  80186. },
  80187. enumerable: true,
  80188. configurable: true
  80189. });
  80190. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  80191. /**
  80192. * Gets the type of tone mapping effect.
  80193. */
  80194. get: function () {
  80195. return this._toneMappingType;
  80196. },
  80197. /**
  80198. * Sets the type of tone mapping effect used in BabylonJS.
  80199. */
  80200. set: function (value) {
  80201. if (this._toneMappingType === value) {
  80202. return;
  80203. }
  80204. this._toneMappingType = value;
  80205. this._updateParameters();
  80206. },
  80207. enumerable: true,
  80208. configurable: true
  80209. });
  80210. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  80211. /**
  80212. * Gets the contrast used in the effect.
  80213. */
  80214. get: function () {
  80215. return this._contrast;
  80216. },
  80217. /**
  80218. * Sets the contrast used in the effect.
  80219. */
  80220. set: function (value) {
  80221. if (this._contrast === value) {
  80222. return;
  80223. }
  80224. this._contrast = value;
  80225. this._updateParameters();
  80226. },
  80227. enumerable: true,
  80228. configurable: true
  80229. });
  80230. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  80231. /**
  80232. * Gets the vignette blend mode allowing different kind of effect.
  80233. */
  80234. get: function () {
  80235. return this._vignetteBlendMode;
  80236. },
  80237. /**
  80238. * Sets the vignette blend mode allowing different kind of effect.
  80239. */
  80240. set: function (value) {
  80241. if (this._vignetteBlendMode === value) {
  80242. return;
  80243. }
  80244. this._vignetteBlendMode = value;
  80245. this._updateParameters();
  80246. },
  80247. enumerable: true,
  80248. configurable: true
  80249. });
  80250. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80251. /**
  80252. * Gets wether the vignette effect is enabled.
  80253. */
  80254. get: function () {
  80255. return this._vignetteEnabled;
  80256. },
  80257. /**
  80258. * Sets wether the vignette effect is enabled.
  80259. */
  80260. set: function (value) {
  80261. if (this._vignetteEnabled === value) {
  80262. return;
  80263. }
  80264. this._vignetteEnabled = value;
  80265. this._updateParameters();
  80266. },
  80267. enumerable: true,
  80268. configurable: true
  80269. });
  80270. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80271. /**
  80272. * Gets wether the image processing is applied through a post process or not.
  80273. */
  80274. get: function () {
  80275. return this._applyByPostProcess;
  80276. },
  80277. /**
  80278. * Sets wether the image processing is applied through a post process or not.
  80279. */
  80280. set: function (value) {
  80281. if (this._applyByPostProcess === value) {
  80282. return;
  80283. }
  80284. this._applyByPostProcess = value;
  80285. this._updateParameters();
  80286. },
  80287. enumerable: true,
  80288. configurable: true
  80289. });
  80290. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80291. /**
  80292. * Gets wether the image processing is enabled or not.
  80293. */
  80294. get: function () {
  80295. return this._isEnabled;
  80296. },
  80297. /**
  80298. * Sets wether the image processing is enabled or not.
  80299. */
  80300. set: function (value) {
  80301. if (this._isEnabled === value) {
  80302. return;
  80303. }
  80304. this._isEnabled = value;
  80305. this._updateParameters();
  80306. },
  80307. enumerable: true,
  80308. configurable: true
  80309. });
  80310. /**
  80311. * Method called each time the image processing information changes requires to recompile the effect.
  80312. */
  80313. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80314. this.onUpdateParameters.notifyObservers(this);
  80315. };
  80316. ImageProcessingConfiguration.prototype.getClassName = function () {
  80317. return "ImageProcessingConfiguration";
  80318. };
  80319. /**
  80320. * Prepare the list of uniforms associated with the Image Processing effects.
  80321. * @param uniformsList The list of uniforms used in the effect
  80322. * @param defines the list of defines currently in use
  80323. */
  80324. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80325. if (defines.EXPOSURE) {
  80326. uniforms.push("exposureLinear");
  80327. }
  80328. if (defines.CONTRAST) {
  80329. uniforms.push("contrast");
  80330. }
  80331. if (defines.COLORGRADING) {
  80332. uniforms.push("colorTransformSettings");
  80333. }
  80334. if (defines.VIGNETTE) {
  80335. uniforms.push("vInverseScreenSize");
  80336. uniforms.push("vignetteSettings1");
  80337. uniforms.push("vignetteSettings2");
  80338. }
  80339. if (defines.COLORCURVES) {
  80340. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80341. }
  80342. };
  80343. /**
  80344. * Prepare the list of samplers associated with the Image Processing effects.
  80345. * @param uniformsList The list of uniforms used in the effect
  80346. * @param defines the list of defines currently in use
  80347. */
  80348. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80349. if (defines.COLORGRADING) {
  80350. samplersList.push("txColorTransform");
  80351. }
  80352. };
  80353. /**
  80354. * Prepare the list of defines associated to the shader.
  80355. * @param defines the list of defines to complete
  80356. */
  80357. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80358. if (forPostProcess === void 0) { forPostProcess = false; }
  80359. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80360. defines.VIGNETTE = false;
  80361. defines.TONEMAPPING = false;
  80362. defines.TONEMAPPING_ACES = false;
  80363. defines.CONTRAST = false;
  80364. defines.EXPOSURE = false;
  80365. defines.COLORCURVES = false;
  80366. defines.COLORGRADING = false;
  80367. defines.COLORGRADING3D = false;
  80368. defines.IMAGEPROCESSING = false;
  80369. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80370. return;
  80371. }
  80372. defines.VIGNETTE = this.vignetteEnabled;
  80373. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80374. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80375. defines.TONEMAPPING = this.toneMappingEnabled;
  80376. switch (this._toneMappingType) {
  80377. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80378. defines.TONEMAPPING_ACES = true;
  80379. break;
  80380. }
  80381. defines.CONTRAST = (this.contrast !== 1.0);
  80382. defines.EXPOSURE = (this.exposure !== 1.0);
  80383. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80384. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80385. if (defines.COLORGRADING) {
  80386. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80387. }
  80388. else {
  80389. defines.COLORGRADING3D = false;
  80390. }
  80391. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80392. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80393. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80394. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80395. };
  80396. /**
  80397. * Returns true if all the image processing information are ready.
  80398. */
  80399. ImageProcessingConfiguration.prototype.isReady = function () {
  80400. // Color Grading texure can not be none blocking.
  80401. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80402. };
  80403. /**
  80404. * Binds the image processing to the shader.
  80405. * @param effect The effect to bind to
  80406. */
  80407. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80408. if (aspectRatio === void 0) { aspectRatio = 1; }
  80409. // Color Curves
  80410. if (this._colorCurvesEnabled && this.colorCurves) {
  80411. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80412. }
  80413. // Vignette
  80414. if (this._vignetteEnabled) {
  80415. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80416. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80417. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80418. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80419. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80420. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80421. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80422. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80423. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80424. var vignettePower = -2.0 * this.vignetteWeight;
  80425. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80426. }
  80427. // Exposure
  80428. effect.setFloat("exposureLinear", this.exposure);
  80429. // Contrast
  80430. effect.setFloat("contrast", this.contrast);
  80431. // Color transform settings
  80432. if (this.colorGradingTexture) {
  80433. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80434. var textureSize = this.colorGradingTexture.getSize().height;
  80435. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80436. 0.5 / textureSize, // textureOffset
  80437. textureSize, // textureSize
  80438. this.colorGradingTexture.level // weight
  80439. );
  80440. }
  80441. };
  80442. /**
  80443. * Clones the current image processing instance.
  80444. * @return The cloned image processing
  80445. */
  80446. ImageProcessingConfiguration.prototype.clone = function () {
  80447. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80448. };
  80449. /**
  80450. * Serializes the current image processing instance to a json representation.
  80451. * @return a JSON representation
  80452. */
  80453. ImageProcessingConfiguration.prototype.serialize = function () {
  80454. return BABYLON.SerializationHelper.Serialize(this);
  80455. };
  80456. /**
  80457. * Parses the image processing from a json representation.
  80458. * @param source the JSON source to parse
  80459. * @return The parsed image processing
  80460. */
  80461. ImageProcessingConfiguration.Parse = function (source) {
  80462. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80463. };
  80464. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80465. /**
  80466. * Used to apply the vignette as a mix with the pixel color.
  80467. */
  80468. get: function () {
  80469. return this._VIGNETTEMODE_MULTIPLY;
  80470. },
  80471. enumerable: true,
  80472. configurable: true
  80473. });
  80474. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80475. /**
  80476. * Used to apply the vignette as a replacement of the pixel color.
  80477. */
  80478. get: function () {
  80479. return this._VIGNETTEMODE_OPAQUE;
  80480. },
  80481. enumerable: true,
  80482. configurable: true
  80483. });
  80484. /**
  80485. * Default tone mapping applied in BabylonJS.
  80486. */
  80487. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80488. /**
  80489. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80490. * to other engines rendering to increase portability.
  80491. */
  80492. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80493. // Static constants associated to the image processing.
  80494. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80495. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80496. __decorate([
  80497. BABYLON.serializeAsColorCurves()
  80498. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80499. __decorate([
  80500. BABYLON.serialize()
  80501. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80502. __decorate([
  80503. BABYLON.serializeAsTexture()
  80504. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80505. __decorate([
  80506. BABYLON.serialize()
  80507. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80508. __decorate([
  80509. BABYLON.serialize()
  80510. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80511. __decorate([
  80512. BABYLON.serialize()
  80513. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  80514. __decorate([
  80515. BABYLON.serialize()
  80516. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  80517. __decorate([
  80518. BABYLON.serialize()
  80519. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  80520. __decorate([
  80521. BABYLON.serialize()
  80522. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  80523. __decorate([
  80524. BABYLON.serialize()
  80525. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  80526. __decorate([
  80527. BABYLON.serialize()
  80528. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  80529. __decorate([
  80530. BABYLON.serialize()
  80531. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  80532. __decorate([
  80533. BABYLON.serialize()
  80534. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  80535. __decorate([
  80536. BABYLON.serialize()
  80537. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  80538. __decorate([
  80539. BABYLON.serializeAsColor4()
  80540. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  80541. __decorate([
  80542. BABYLON.serialize()
  80543. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  80544. __decorate([
  80545. BABYLON.serialize()
  80546. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  80547. __decorate([
  80548. BABYLON.serialize()
  80549. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  80550. __decorate([
  80551. BABYLON.serialize()
  80552. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  80553. __decorate([
  80554. BABYLON.serialize()
  80555. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  80556. return ImageProcessingConfiguration;
  80557. }());
  80558. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  80559. })(BABYLON || (BABYLON = {}));
  80560. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  80561. var BABYLON;
  80562. (function (BABYLON) {
  80563. /**
  80564. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  80565. * It can help converting any input color in a desired output one. This can then be used to create effects
  80566. * from sepia, black and white to sixties or futuristic rendering...
  80567. *
  80568. * The only supported format is currently 3dl.
  80569. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  80570. */
  80571. var ColorGradingTexture = /** @class */ (function (_super) {
  80572. __extends(ColorGradingTexture, _super);
  80573. /**
  80574. * Instantiates a ColorGradingTexture from the following parameters.
  80575. *
  80576. * @param url The location of the color gradind data (currently only supporting 3dl)
  80577. * @param scene The scene the texture will be used in
  80578. */
  80579. function ColorGradingTexture(url, scene) {
  80580. var _this = _super.call(this, scene) || this;
  80581. if (!url) {
  80582. return _this;
  80583. }
  80584. _this._engine = scene.getEngine();
  80585. _this._textureMatrix = BABYLON.Matrix.Identity();
  80586. _this.name = url;
  80587. _this.url = url;
  80588. _this.hasAlpha = false;
  80589. _this.isCube = false;
  80590. _this.is3D = _this._engine.webGLVersion > 1;
  80591. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80592. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80593. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80594. _this.anisotropicFilteringLevel = 1;
  80595. _this._texture = _this._getFromCache(url, true);
  80596. if (!_this._texture) {
  80597. if (!scene.useDelayedTextureLoading) {
  80598. _this.loadTexture();
  80599. }
  80600. else {
  80601. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80602. }
  80603. }
  80604. return _this;
  80605. }
  80606. /**
  80607. * Returns the texture matrix used in most of the material.
  80608. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  80609. */
  80610. ColorGradingTexture.prototype.getTextureMatrix = function () {
  80611. return this._textureMatrix;
  80612. };
  80613. /**
  80614. * Occurs when the file being loaded is a .3dl LUT file.
  80615. */
  80616. ColorGradingTexture.prototype.load3dlTexture = function () {
  80617. var engine = this._engine;
  80618. var texture;
  80619. if (engine.webGLVersion === 1) {
  80620. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80621. }
  80622. else {
  80623. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80624. }
  80625. this._texture = texture;
  80626. var callback = function (text) {
  80627. if (typeof text !== "string") {
  80628. return;
  80629. }
  80630. var data = null;
  80631. var tempData = null;
  80632. var line;
  80633. var lines = text.split('\n');
  80634. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  80635. var maxColor = 0;
  80636. for (var i = 0; i < lines.length; i++) {
  80637. line = lines[i];
  80638. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  80639. continue;
  80640. if (line.indexOf('#') === 0)
  80641. continue;
  80642. var words = line.split(" ");
  80643. if (size === 0) {
  80644. // Number of space + one
  80645. size = words.length;
  80646. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  80647. tempData = new Float32Array(size * size * size * 4);
  80648. continue;
  80649. }
  80650. if (size != 0) {
  80651. var r = Math.max(parseInt(words[0]), 0);
  80652. var g = Math.max(parseInt(words[1]), 0);
  80653. var b = Math.max(parseInt(words[2]), 0);
  80654. maxColor = Math.max(r, maxColor);
  80655. maxColor = Math.max(g, maxColor);
  80656. maxColor = Math.max(b, maxColor);
  80657. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  80658. if (tempData) {
  80659. tempData[pixelStorageIndex + 0] = r;
  80660. tempData[pixelStorageIndex + 1] = g;
  80661. tempData[pixelStorageIndex + 2] = b;
  80662. }
  80663. pixelIndexSlice++;
  80664. if (pixelIndexSlice % size == 0) {
  80665. pixelIndexH++;
  80666. pixelIndexSlice = 0;
  80667. if (pixelIndexH % size == 0) {
  80668. pixelIndexW++;
  80669. pixelIndexH = 0;
  80670. }
  80671. }
  80672. }
  80673. }
  80674. if (tempData && data) {
  80675. for (var i = 0; i < tempData.length; i++) {
  80676. if (i > 0 && (i + 1) % 4 === 0) {
  80677. data[i] = 255;
  80678. }
  80679. else {
  80680. var value = tempData[i];
  80681. data[i] = (value / maxColor * 255);
  80682. }
  80683. }
  80684. }
  80685. if (texture.is3D) {
  80686. texture.updateSize(size, size, size);
  80687. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80688. }
  80689. else {
  80690. texture.updateSize(size * size, size);
  80691. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80692. }
  80693. };
  80694. var scene = this.getScene();
  80695. if (scene) {
  80696. scene._loadFile(this.url, callback);
  80697. }
  80698. else {
  80699. this._engine._loadFile(this.url, callback);
  80700. }
  80701. return this._texture;
  80702. };
  80703. /**
  80704. * Starts the loading process of the texture.
  80705. */
  80706. ColorGradingTexture.prototype.loadTexture = function () {
  80707. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  80708. this.load3dlTexture();
  80709. }
  80710. };
  80711. /**
  80712. * Clones the color gradind texture.
  80713. */
  80714. ColorGradingTexture.prototype.clone = function () {
  80715. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  80716. // Base texture
  80717. newTexture.level = this.level;
  80718. return newTexture;
  80719. };
  80720. /**
  80721. * Called during delayed load for textures.
  80722. */
  80723. ColorGradingTexture.prototype.delayLoad = function () {
  80724. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80725. return;
  80726. }
  80727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80728. this._texture = this._getFromCache(this.url, true);
  80729. if (!this._texture) {
  80730. this.loadTexture();
  80731. }
  80732. };
  80733. /**
  80734. * Parses a color grading texture serialized by Babylon.
  80735. * @param parsedTexture The texture information being parsedTexture
  80736. * @param scene The scene to load the texture in
  80737. * @param rootUrl The root url of the data assets to load
  80738. * @return A color gradind texture
  80739. */
  80740. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80741. var texture = null;
  80742. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80743. texture = new ColorGradingTexture(parsedTexture.name, scene);
  80744. texture.name = parsedTexture.name;
  80745. texture.level = parsedTexture.level;
  80746. }
  80747. return texture;
  80748. };
  80749. /**
  80750. * Serializes the LUT texture to json format.
  80751. */
  80752. ColorGradingTexture.prototype.serialize = function () {
  80753. if (!this.name) {
  80754. return null;
  80755. }
  80756. var serializationObject = {};
  80757. serializationObject.name = this.name;
  80758. serializationObject.level = this.level;
  80759. serializationObject.customType = "BABYLON.ColorGradingTexture";
  80760. return serializationObject;
  80761. };
  80762. /**
  80763. * Empty line regex stored for GC.
  80764. */
  80765. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  80766. return ColorGradingTexture;
  80767. }(BABYLON.BaseTexture));
  80768. BABYLON.ColorGradingTexture = ColorGradingTexture;
  80769. })(BABYLON || (BABYLON = {}));
  80770. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  80771. var BABYLON;
  80772. (function (BABYLON) {
  80773. /**
  80774. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80775. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80776. * 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;
  80777. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80778. */
  80779. var ColorCurves = /** @class */ (function () {
  80780. function ColorCurves() {
  80781. this._dirty = true;
  80782. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  80783. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  80784. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  80785. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  80786. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  80787. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  80788. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  80789. this._globalHue = 30;
  80790. this._globalDensity = 0;
  80791. this._globalSaturation = 0;
  80792. this._globalExposure = 0;
  80793. this._highlightsHue = 30;
  80794. this._highlightsDensity = 0;
  80795. this._highlightsSaturation = 0;
  80796. this._highlightsExposure = 0;
  80797. this._midtonesHue = 30;
  80798. this._midtonesDensity = 0;
  80799. this._midtonesSaturation = 0;
  80800. this._midtonesExposure = 0;
  80801. this._shadowsHue = 30;
  80802. this._shadowsDensity = 0;
  80803. this._shadowsSaturation = 0;
  80804. this._shadowsExposure = 0;
  80805. }
  80806. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  80807. /**
  80808. * Gets the global Hue value.
  80809. * 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).
  80810. */
  80811. get: function () {
  80812. return this._globalHue;
  80813. },
  80814. /**
  80815. * Sets the global Hue value.
  80816. * 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).
  80817. */
  80818. set: function (value) {
  80819. this._globalHue = value;
  80820. this._dirty = true;
  80821. },
  80822. enumerable: true,
  80823. configurable: true
  80824. });
  80825. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  80826. /**
  80827. * Gets the global Density value.
  80828. * 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.
  80829. * Values less than zero provide a filter of opposite hue.
  80830. */
  80831. get: function () {
  80832. return this._globalDensity;
  80833. },
  80834. /**
  80835. * Sets the global Density value.
  80836. * 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.
  80837. * Values less than zero provide a filter of opposite hue.
  80838. */
  80839. set: function (value) {
  80840. this._globalDensity = value;
  80841. this._dirty = true;
  80842. },
  80843. enumerable: true,
  80844. configurable: true
  80845. });
  80846. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  80847. /**
  80848. * Gets the global Saturation value.
  80849. * 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.
  80850. */
  80851. get: function () {
  80852. return this._globalSaturation;
  80853. },
  80854. /**
  80855. * Sets the global Saturation value.
  80856. * 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.
  80857. */
  80858. set: function (value) {
  80859. this._globalSaturation = value;
  80860. this._dirty = true;
  80861. },
  80862. enumerable: true,
  80863. configurable: true
  80864. });
  80865. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  80866. /**
  80867. * Gets the global Exposure value.
  80868. * 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.
  80869. */
  80870. get: function () {
  80871. return this._globalExposure;
  80872. },
  80873. /**
  80874. * Sets the global Exposure value.
  80875. * 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.
  80876. */
  80877. set: function (value) {
  80878. this._globalExposure = value;
  80879. this._dirty = true;
  80880. },
  80881. enumerable: true,
  80882. configurable: true
  80883. });
  80884. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  80885. /**
  80886. * Gets the highlights Hue value.
  80887. * 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).
  80888. */
  80889. get: function () {
  80890. return this._highlightsHue;
  80891. },
  80892. /**
  80893. * Sets the highlights Hue value.
  80894. * 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).
  80895. */
  80896. set: function (value) {
  80897. this._highlightsHue = value;
  80898. this._dirty = true;
  80899. },
  80900. enumerable: true,
  80901. configurable: true
  80902. });
  80903. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  80904. /**
  80905. * Gets the highlights Density value.
  80906. * 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.
  80907. * Values less than zero provide a filter of opposite hue.
  80908. */
  80909. get: function () {
  80910. return this._highlightsDensity;
  80911. },
  80912. /**
  80913. * Sets the highlights Density value.
  80914. * 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.
  80915. * Values less than zero provide a filter of opposite hue.
  80916. */
  80917. set: function (value) {
  80918. this._highlightsDensity = value;
  80919. this._dirty = true;
  80920. },
  80921. enumerable: true,
  80922. configurable: true
  80923. });
  80924. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  80925. /**
  80926. * Gets the highlights Saturation value.
  80927. * 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.
  80928. */
  80929. get: function () {
  80930. return this._highlightsSaturation;
  80931. },
  80932. /**
  80933. * Sets the highlights Saturation value.
  80934. * 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.
  80935. */
  80936. set: function (value) {
  80937. this._highlightsSaturation = value;
  80938. this._dirty = true;
  80939. },
  80940. enumerable: true,
  80941. configurable: true
  80942. });
  80943. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  80944. /**
  80945. * Gets the highlights Exposure value.
  80946. * 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.
  80947. */
  80948. get: function () {
  80949. return this._highlightsExposure;
  80950. },
  80951. /**
  80952. * Sets the highlights Exposure value.
  80953. * 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.
  80954. */
  80955. set: function (value) {
  80956. this._highlightsExposure = value;
  80957. this._dirty = true;
  80958. },
  80959. enumerable: true,
  80960. configurable: true
  80961. });
  80962. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  80963. /**
  80964. * Gets the midtones Hue value.
  80965. * 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).
  80966. */
  80967. get: function () {
  80968. return this._midtonesHue;
  80969. },
  80970. /**
  80971. * Sets the midtones Hue value.
  80972. * 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).
  80973. */
  80974. set: function (value) {
  80975. this._midtonesHue = value;
  80976. this._dirty = true;
  80977. },
  80978. enumerable: true,
  80979. configurable: true
  80980. });
  80981. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  80982. /**
  80983. * Gets the midtones Density value.
  80984. * 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.
  80985. * Values less than zero provide a filter of opposite hue.
  80986. */
  80987. get: function () {
  80988. return this._midtonesDensity;
  80989. },
  80990. /**
  80991. * Sets the midtones Density value.
  80992. * 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.
  80993. * Values less than zero provide a filter of opposite hue.
  80994. */
  80995. set: function (value) {
  80996. this._midtonesDensity = value;
  80997. this._dirty = true;
  80998. },
  80999. enumerable: true,
  81000. configurable: true
  81001. });
  81002. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81003. /**
  81004. * Gets the midtones Saturation value.
  81005. * 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.
  81006. */
  81007. get: function () {
  81008. return this._midtonesSaturation;
  81009. },
  81010. /**
  81011. * Sets the midtones Saturation value.
  81012. * 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.
  81013. */
  81014. set: function (value) {
  81015. this._midtonesSaturation = value;
  81016. this._dirty = true;
  81017. },
  81018. enumerable: true,
  81019. configurable: true
  81020. });
  81021. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81022. /**
  81023. * Gets the midtones Exposure value.
  81024. * 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.
  81025. */
  81026. get: function () {
  81027. return this._midtonesExposure;
  81028. },
  81029. /**
  81030. * Sets the midtones Exposure value.
  81031. * 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.
  81032. */
  81033. set: function (value) {
  81034. this._midtonesExposure = value;
  81035. this._dirty = true;
  81036. },
  81037. enumerable: true,
  81038. configurable: true
  81039. });
  81040. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81041. /**
  81042. * Gets the shadows Hue value.
  81043. * 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).
  81044. */
  81045. get: function () {
  81046. return this._shadowsHue;
  81047. },
  81048. /**
  81049. * Sets the shadows Hue value.
  81050. * 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).
  81051. */
  81052. set: function (value) {
  81053. this._shadowsHue = value;
  81054. this._dirty = true;
  81055. },
  81056. enumerable: true,
  81057. configurable: true
  81058. });
  81059. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81060. /**
  81061. * Gets the shadows Density value.
  81062. * 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.
  81063. * Values less than zero provide a filter of opposite hue.
  81064. */
  81065. get: function () {
  81066. return this._shadowsDensity;
  81067. },
  81068. /**
  81069. * Sets the shadows Density value.
  81070. * 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.
  81071. * Values less than zero provide a filter of opposite hue.
  81072. */
  81073. set: function (value) {
  81074. this._shadowsDensity = value;
  81075. this._dirty = true;
  81076. },
  81077. enumerable: true,
  81078. configurable: true
  81079. });
  81080. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81081. /**
  81082. * Gets the shadows Saturation value.
  81083. * 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.
  81084. */
  81085. get: function () {
  81086. return this._shadowsSaturation;
  81087. },
  81088. /**
  81089. * Sets the shadows Saturation value.
  81090. * 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.
  81091. */
  81092. set: function (value) {
  81093. this._shadowsSaturation = value;
  81094. this._dirty = true;
  81095. },
  81096. enumerable: true,
  81097. configurable: true
  81098. });
  81099. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  81100. /**
  81101. * Gets the shadows Exposure value.
  81102. * 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.
  81103. */
  81104. get: function () {
  81105. return this._shadowsExposure;
  81106. },
  81107. /**
  81108. * Sets the shadows Exposure value.
  81109. * 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.
  81110. */
  81111. set: function (value) {
  81112. this._shadowsExposure = value;
  81113. this._dirty = true;
  81114. },
  81115. enumerable: true,
  81116. configurable: true
  81117. });
  81118. ColorCurves.prototype.getClassName = function () {
  81119. return "ColorCurves";
  81120. };
  81121. /**
  81122. * Binds the color curves to the shader.
  81123. * @param colorCurves The color curve to bind
  81124. * @param effect The effect to bind to
  81125. */
  81126. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  81127. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  81128. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  81129. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  81130. if (colorCurves._dirty) {
  81131. colorCurves._dirty = false;
  81132. // Fill in global info.
  81133. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  81134. // Compute highlights info.
  81135. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  81136. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  81137. // Compute midtones info.
  81138. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  81139. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  81140. // Compute shadows info.
  81141. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  81142. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  81143. // Compute deltas (neutral is midtones).
  81144. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  81145. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  81146. }
  81147. if (effect) {
  81148. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  81149. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  81150. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  81151. }
  81152. };
  81153. /**
  81154. * Prepare the list of uniforms associated with the ColorCurves effects.
  81155. * @param uniformsList The list of uniforms used in the effect
  81156. */
  81157. ColorCurves.PrepareUniforms = function (uniformsList) {
  81158. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  81159. };
  81160. /**
  81161. * Returns color grading data based on a hue, density, saturation and exposure value.
  81162. * @param filterHue The hue of the color filter.
  81163. * @param filterDensity The density of the color filter.
  81164. * @param saturation The saturation.
  81165. * @param exposure The exposure.
  81166. * @param result The result data container.
  81167. */
  81168. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  81169. if (hue == null) {
  81170. return;
  81171. }
  81172. hue = ColorCurves.clamp(hue, 0, 360);
  81173. density = ColorCurves.clamp(density, -100, 100);
  81174. saturation = ColorCurves.clamp(saturation, -100, 100);
  81175. exposure = ColorCurves.clamp(exposure, -100, 100);
  81176. // Remap the slider/config filter density with non-linear mapping and also scale by half
  81177. // so that the maximum filter density is only 50% control. This provides fine control
  81178. // for small values and reasonable range.
  81179. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  81180. density *= 0.5;
  81181. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  81182. if (density < 0) {
  81183. density *= -1;
  81184. hue = (hue + 180) % 360;
  81185. }
  81186. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  81187. result.scaleToRef(2, result);
  81188. result.a = 1 + 0.01 * saturation;
  81189. };
  81190. /**
  81191. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  81192. * @param value The input slider value in range [-100,100].
  81193. * @returns Adjusted value.
  81194. */
  81195. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  81196. value /= 100;
  81197. var x = Math.abs(value);
  81198. x = Math.pow(x, 2);
  81199. if (value < 0) {
  81200. x *= -1;
  81201. }
  81202. x *= 100;
  81203. return x;
  81204. };
  81205. /**
  81206. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  81207. * @param hue The hue (H) input.
  81208. * @param saturation The saturation (S) input.
  81209. * @param brightness The brightness (B) input.
  81210. * @result An RGBA color represented as Vector4.
  81211. */
  81212. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  81213. var h = ColorCurves.clamp(hue, 0, 360);
  81214. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  81215. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  81216. if (s === 0) {
  81217. result.r = v;
  81218. result.g = v;
  81219. result.b = v;
  81220. }
  81221. else {
  81222. // sector 0 to 5
  81223. h /= 60;
  81224. var i = Math.floor(h);
  81225. // fractional part of h
  81226. var f = h - i;
  81227. var p = v * (1 - s);
  81228. var q = v * (1 - s * f);
  81229. var t = v * (1 - s * (1 - f));
  81230. switch (i) {
  81231. case 0:
  81232. result.r = v;
  81233. result.g = t;
  81234. result.b = p;
  81235. break;
  81236. case 1:
  81237. result.r = q;
  81238. result.g = v;
  81239. result.b = p;
  81240. break;
  81241. case 2:
  81242. result.r = p;
  81243. result.g = v;
  81244. result.b = t;
  81245. break;
  81246. case 3:
  81247. result.r = p;
  81248. result.g = q;
  81249. result.b = v;
  81250. break;
  81251. case 4:
  81252. result.r = t;
  81253. result.g = p;
  81254. result.b = v;
  81255. break;
  81256. default: // case 5:
  81257. result.r = v;
  81258. result.g = p;
  81259. result.b = q;
  81260. break;
  81261. }
  81262. }
  81263. result.a = 1;
  81264. };
  81265. /**
  81266. * Returns a value clamped between min and max
  81267. * @param value The value to clamp
  81268. * @param min The minimum of value
  81269. * @param max The maximum of value
  81270. * @returns The clamped value.
  81271. */
  81272. ColorCurves.clamp = function (value, min, max) {
  81273. return Math.min(Math.max(value, min), max);
  81274. };
  81275. /**
  81276. * Clones the current color curve instance.
  81277. * @return The cloned curves
  81278. */
  81279. ColorCurves.prototype.clone = function () {
  81280. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81281. };
  81282. /**
  81283. * Serializes the current color curve instance to a json representation.
  81284. * @return a JSON representation
  81285. */
  81286. ColorCurves.prototype.serialize = function () {
  81287. return BABYLON.SerializationHelper.Serialize(this);
  81288. };
  81289. /**
  81290. * Parses the color curve from a json representation.
  81291. * @param source the JSON source to parse
  81292. * @return The parsed curves
  81293. */
  81294. ColorCurves.Parse = function (source) {
  81295. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81296. };
  81297. __decorate([
  81298. BABYLON.serialize()
  81299. ], ColorCurves.prototype, "_globalHue", void 0);
  81300. __decorate([
  81301. BABYLON.serialize()
  81302. ], ColorCurves.prototype, "_globalDensity", void 0);
  81303. __decorate([
  81304. BABYLON.serialize()
  81305. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81306. __decorate([
  81307. BABYLON.serialize()
  81308. ], ColorCurves.prototype, "_globalExposure", void 0);
  81309. __decorate([
  81310. BABYLON.serialize()
  81311. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81312. __decorate([
  81313. BABYLON.serialize()
  81314. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81315. __decorate([
  81316. BABYLON.serialize()
  81317. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81318. __decorate([
  81319. BABYLON.serialize()
  81320. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81321. __decorate([
  81322. BABYLON.serialize()
  81323. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81324. __decorate([
  81325. BABYLON.serialize()
  81326. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81327. __decorate([
  81328. BABYLON.serialize()
  81329. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81330. __decorate([
  81331. BABYLON.serialize()
  81332. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81333. return ColorCurves;
  81334. }());
  81335. BABYLON.ColorCurves = ColorCurves;
  81336. })(BABYLON || (BABYLON = {}));
  81337. //# sourceMappingURL=babylon.colorCurves.js.map
  81338. var BABYLON;
  81339. (function (BABYLON) {
  81340. var RefractionPostProcess = /** @class */ (function (_super) {
  81341. __extends(RefractionPostProcess, _super);
  81342. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81343. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81344. _this.color = color;
  81345. _this.depth = depth;
  81346. _this.colorLevel = colorLevel;
  81347. _this._ownRefractionTexture = true;
  81348. _this.onActivateObservable.add(function (cam) {
  81349. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81350. });
  81351. _this.onApplyObservable.add(function (effect) {
  81352. effect.setColor3("baseColor", _this.color);
  81353. effect.setFloat("depth", _this.depth);
  81354. effect.setFloat("colorLevel", _this.colorLevel);
  81355. effect.setTexture("refractionSampler", _this._refTexture);
  81356. });
  81357. return _this;
  81358. }
  81359. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81360. /**
  81361. * Gets or sets the refraction texture
  81362. * Please note that you are responsible for disposing the texture if you set it manually
  81363. */
  81364. get: function () {
  81365. return this._refTexture;
  81366. },
  81367. set: function (value) {
  81368. if (this._refTexture && this._ownRefractionTexture) {
  81369. this._refTexture.dispose();
  81370. }
  81371. this._refTexture = value;
  81372. this._ownRefractionTexture = false;
  81373. },
  81374. enumerable: true,
  81375. configurable: true
  81376. });
  81377. // Methods
  81378. RefractionPostProcess.prototype.dispose = function (camera) {
  81379. if (this._refTexture && this._ownRefractionTexture) {
  81380. this._refTexture.dispose();
  81381. this._refTexture = null;
  81382. }
  81383. _super.prototype.dispose.call(this, camera);
  81384. };
  81385. return RefractionPostProcess;
  81386. }(BABYLON.PostProcess));
  81387. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81388. })(BABYLON || (BABYLON = {}));
  81389. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81390. var BABYLON;
  81391. (function (BABYLON) {
  81392. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81393. __extends(BlackAndWhitePostProcess, _super);
  81394. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81395. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81396. _this.degree = 1;
  81397. _this.onApplyObservable.add(function (effect) {
  81398. effect.setFloat("degree", _this.degree);
  81399. });
  81400. return _this;
  81401. }
  81402. return BlackAndWhitePostProcess;
  81403. }(BABYLON.PostProcess));
  81404. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81405. })(BABYLON || (BABYLON = {}));
  81406. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81407. var BABYLON;
  81408. (function (BABYLON) {
  81409. /**
  81410. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81411. * input texture to perform effects such as edge detection or sharpening
  81412. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81413. */
  81414. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81415. __extends(ConvolutionPostProcess, _super);
  81416. /**
  81417. * Creates a new instance ConvolutionPostProcess
  81418. * @param name The name of the effect.
  81419. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81420. * @param options The required width/height ratio to downsize to before computing the render pass.
  81421. * @param camera The camera to apply the render pass to.
  81422. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81423. * @param engine The engine which the post process will be applied. (default: current engine)
  81424. * @param reusable If the post process can be reused on the same frame. (default: false)
  81425. * @param textureType Type of textures used when performing the post process. (default: 0)
  81426. */
  81427. function ConvolutionPostProcess(name,
  81428. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81429. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81430. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81431. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81432. _this.kernel = kernel;
  81433. _this.onApply = function (effect) {
  81434. effect.setFloat2("screenSize", _this.width, _this.height);
  81435. effect.setArray("kernel", _this.kernel);
  81436. };
  81437. return _this;
  81438. }
  81439. // Statics
  81440. /**
  81441. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81442. */
  81443. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81444. /**
  81445. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81446. */
  81447. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81448. /**
  81449. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81450. */
  81451. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81452. /**
  81453. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81454. */
  81455. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81456. /**
  81457. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81458. */
  81459. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81460. /**
  81461. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81462. */
  81463. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81464. return ConvolutionPostProcess;
  81465. }(BABYLON.PostProcess));
  81466. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81467. })(BABYLON || (BABYLON = {}));
  81468. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81469. var BABYLON;
  81470. (function (BABYLON) {
  81471. var FilterPostProcess = /** @class */ (function (_super) {
  81472. __extends(FilterPostProcess, _super);
  81473. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81474. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81475. _this.kernelMatrix = kernelMatrix;
  81476. _this.onApply = function (effect) {
  81477. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81478. };
  81479. return _this;
  81480. }
  81481. return FilterPostProcess;
  81482. }(BABYLON.PostProcess));
  81483. BABYLON.FilterPostProcess = FilterPostProcess;
  81484. })(BABYLON || (BABYLON = {}));
  81485. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81486. var BABYLON;
  81487. (function (BABYLON) {
  81488. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81489. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81490. __extends(VolumetricLightScatteringPostProcess, _super);
  81491. /**
  81492. * @constructor
  81493. * @param {string} name - The post-process name
  81494. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  81495. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81496. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81497. * @param {number} samples - The post-process quality, default 100
  81498. * @param {number} samplingMode - The post-process filtering mode
  81499. * @param {BABYLON.Engine} engine - The babylon engine
  81500. * @param {boolean} reusable - If the post-process is reusable
  81501. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  81502. */
  81503. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81504. if (samples === void 0) { samples = 100; }
  81505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81506. 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;
  81507. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81508. /**
  81509. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81510. */
  81511. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81512. /**
  81513. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  81514. */
  81515. _this.useCustomMeshPosition = false;
  81516. /**
  81517. * If the post-process should inverse the light scattering direction
  81518. */
  81519. _this.invert = true;
  81520. /**
  81521. * Array containing the excluded meshes not rendered in the internal pass
  81522. */
  81523. _this.excludedMeshes = new Array();
  81524. /**
  81525. * Controls the overall intensity of the post-process
  81526. */
  81527. _this.exposure = 0.3;
  81528. /**
  81529. * Dissipates each sample's contribution in range [0, 1]
  81530. */
  81531. _this.decay = 0.96815;
  81532. /**
  81533. * Controls the overall intensity of each sample
  81534. */
  81535. _this.weight = 0.58767;
  81536. /**
  81537. * Controls the density of each sample
  81538. */
  81539. _this.density = 0.926;
  81540. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  81541. engine = scene.getEngine();
  81542. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  81543. // Configure mesh
  81544. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  81545. // Configure
  81546. _this._createPass(scene, ratio.passRatio || ratio);
  81547. _this.onActivate = function (camera) {
  81548. if (!_this.isSupported) {
  81549. _this.dispose(camera);
  81550. }
  81551. _this.onActivate = null;
  81552. };
  81553. _this.onApplyObservable.add(function (effect) {
  81554. _this._updateMeshScreenCoordinates(scene);
  81555. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  81556. effect.setFloat("exposure", _this.exposure);
  81557. effect.setFloat("decay", _this.decay);
  81558. effect.setFloat("weight", _this.weight);
  81559. effect.setFloat("density", _this.density);
  81560. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  81561. });
  81562. return _this;
  81563. }
  81564. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  81565. get: function () {
  81566. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81567. return false;
  81568. },
  81569. set: function (useDiffuseColor) {
  81570. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81571. },
  81572. enumerable: true,
  81573. configurable: true
  81574. });
  81575. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  81576. return "VolumetricLightScatteringPostProcess";
  81577. };
  81578. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  81579. var mesh = subMesh.getMesh();
  81580. // Render this.mesh as default
  81581. if (mesh === this.mesh && mesh.material) {
  81582. return mesh.material.isReady(mesh);
  81583. }
  81584. var defines = [];
  81585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81586. var material = subMesh.getMaterial();
  81587. // Alpha test
  81588. if (material) {
  81589. if (material.needAlphaTesting()) {
  81590. defines.push("#define ALPHATEST");
  81591. }
  81592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81593. attribs.push(BABYLON.VertexBuffer.UVKind);
  81594. defines.push("#define UV1");
  81595. }
  81596. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81597. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81598. defines.push("#define UV2");
  81599. }
  81600. }
  81601. // Bones
  81602. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81603. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81604. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81606. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81607. }
  81608. else {
  81609. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81610. }
  81611. // Instances
  81612. if (useInstances) {
  81613. defines.push("#define INSTANCES");
  81614. attribs.push("world0");
  81615. attribs.push("world1");
  81616. attribs.push("world2");
  81617. attribs.push("world3");
  81618. }
  81619. // Get correct effect
  81620. var join = defines.join("\n");
  81621. if (this._cachedDefines !== join) {
  81622. this._cachedDefines = join;
  81623. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  81624. }
  81625. return this._volumetricLightScatteringPass.isReady();
  81626. };
  81627. /**
  81628. * Sets the new light position for light scattering effect
  81629. * @param {BABYLON.Vector3} The new custom light position
  81630. */
  81631. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  81632. this.customMeshPosition = position;
  81633. };
  81634. /**
  81635. * Returns the light position for light scattering effect
  81636. * @return {BABYLON.Vector3} The custom light position
  81637. */
  81638. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  81639. return this.customMeshPosition;
  81640. };
  81641. /**
  81642. * Disposes the internal assets and detaches the post-process from the camera
  81643. */
  81644. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  81645. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  81646. if (rttIndex !== -1) {
  81647. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  81648. }
  81649. this._volumetricLightScatteringRTT.dispose();
  81650. _super.prototype.dispose.call(this, camera);
  81651. };
  81652. /**
  81653. * Returns the render target texture used by the post-process
  81654. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  81655. */
  81656. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  81657. return this._volumetricLightScatteringRTT;
  81658. };
  81659. // Private methods
  81660. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  81661. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  81662. return true;
  81663. }
  81664. return false;
  81665. };
  81666. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  81667. var _this = this;
  81668. var engine = scene.getEngine();
  81669. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81670. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81671. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81672. this._volumetricLightScatteringRTT.renderList = null;
  81673. this._volumetricLightScatteringRTT.renderParticles = false;
  81674. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  81675. var camera = this.getCamera();
  81676. if (camera) {
  81677. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81678. }
  81679. else {
  81680. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81681. }
  81682. // Custom render function for submeshes
  81683. var renderSubMesh = function (subMesh) {
  81684. var mesh = subMesh.getRenderingMesh();
  81685. if (_this._meshExcluded(mesh)) {
  81686. return;
  81687. }
  81688. var material = subMesh.getMaterial();
  81689. if (!material) {
  81690. return;
  81691. }
  81692. var scene = mesh.getScene();
  81693. var engine = scene.getEngine();
  81694. // Culling
  81695. engine.setState(material.backFaceCulling);
  81696. // Managing instances
  81697. var batch = mesh._getInstancesRenderList(subMesh._id);
  81698. if (batch.mustReturn) {
  81699. return;
  81700. }
  81701. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81702. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  81703. var effect = _this._volumetricLightScatteringPass;
  81704. if (mesh === _this.mesh) {
  81705. if (subMesh.effect) {
  81706. effect = subMesh.effect;
  81707. }
  81708. else {
  81709. effect = material.getEffect();
  81710. }
  81711. }
  81712. engine.enableEffect(effect);
  81713. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  81714. if (mesh === _this.mesh) {
  81715. material.bind(mesh.getWorldMatrix(), mesh);
  81716. }
  81717. else {
  81718. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  81719. // Alpha test
  81720. if (material && material.needAlphaTesting()) {
  81721. var alphaTexture = material.getAlphaTestTexture();
  81722. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  81723. if (alphaTexture) {
  81724. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81725. }
  81726. }
  81727. // Bones
  81728. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81729. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81730. }
  81731. }
  81732. // Draw
  81733. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  81734. }
  81735. };
  81736. // Render target texture callbacks
  81737. var savedSceneClearColor;
  81738. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  81739. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  81740. savedSceneClearColor = scene.clearColor;
  81741. scene.clearColor = sceneClearColor;
  81742. });
  81743. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  81744. scene.clearColor = savedSceneClearColor;
  81745. });
  81746. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81747. var engine = scene.getEngine();
  81748. var index;
  81749. if (depthOnlySubMeshes.length) {
  81750. engine.setColorWrite(false);
  81751. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81752. renderSubMesh(depthOnlySubMeshes.data[index]);
  81753. }
  81754. engine.setColorWrite(true);
  81755. }
  81756. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81757. renderSubMesh(opaqueSubMeshes.data[index]);
  81758. }
  81759. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81760. renderSubMesh(alphaTestSubMeshes.data[index]);
  81761. }
  81762. if (transparentSubMeshes.length) {
  81763. // Sort sub meshes
  81764. for (index = 0; index < transparentSubMeshes.length; index++) {
  81765. var submesh = transparentSubMeshes.data[index];
  81766. var boundingInfo = submesh.getBoundingInfo();
  81767. if (boundingInfo && scene.activeCamera) {
  81768. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  81769. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  81770. }
  81771. }
  81772. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  81773. sortedArray.sort(function (a, b) {
  81774. // Alpha index first
  81775. if (a._alphaIndex > b._alphaIndex) {
  81776. return 1;
  81777. }
  81778. if (a._alphaIndex < b._alphaIndex) {
  81779. return -1;
  81780. }
  81781. // Then distance to camera
  81782. if (a._distanceToCamera < b._distanceToCamera) {
  81783. return 1;
  81784. }
  81785. if (a._distanceToCamera > b._distanceToCamera) {
  81786. return -1;
  81787. }
  81788. return 0;
  81789. });
  81790. // Render sub meshes
  81791. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  81792. for (index = 0; index < sortedArray.length; index++) {
  81793. renderSubMesh(sortedArray[index]);
  81794. }
  81795. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81796. }
  81797. };
  81798. };
  81799. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  81800. var transform = scene.getTransformMatrix();
  81801. var meshPosition;
  81802. if (this.useCustomMeshPosition) {
  81803. meshPosition = this.customMeshPosition;
  81804. }
  81805. else if (this.attachedNode) {
  81806. meshPosition = this.attachedNode.position;
  81807. }
  81808. else {
  81809. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  81810. }
  81811. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  81812. this._screenCoordinates.x = pos.x / this._viewPort.width;
  81813. this._screenCoordinates.y = pos.y / this._viewPort.height;
  81814. if (this.invert)
  81815. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  81816. };
  81817. // Static methods
  81818. /**
  81819. * Creates a default mesh for the Volumeric Light Scattering post-process
  81820. * @param {string} The mesh name
  81821. * @param {BABYLON.Scene} The scene where to create the mesh
  81822. * @return {BABYLON.Mesh} the default mesh
  81823. */
  81824. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  81825. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  81826. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  81827. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  81828. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  81829. mesh.material = material;
  81830. return mesh;
  81831. };
  81832. __decorate([
  81833. BABYLON.serializeAsVector3()
  81834. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  81835. __decorate([
  81836. BABYLON.serialize()
  81837. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  81838. __decorate([
  81839. BABYLON.serialize()
  81840. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  81841. __decorate([
  81842. BABYLON.serializeAsMeshReference()
  81843. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  81844. __decorate([
  81845. BABYLON.serialize()
  81846. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  81847. __decorate([
  81848. BABYLON.serialize()
  81849. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  81850. __decorate([
  81851. BABYLON.serialize()
  81852. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  81853. __decorate([
  81854. BABYLON.serialize()
  81855. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  81856. __decorate([
  81857. BABYLON.serialize()
  81858. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  81859. return VolumetricLightScatteringPostProcess;
  81860. }(BABYLON.PostProcess));
  81861. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  81862. })(BABYLON || (BABYLON = {}));
  81863. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  81864. //
  81865. // This post-process allows the modification of rendered colors by using
  81866. // a 'look-up table' (LUT). This effect is also called Color Grading.
  81867. //
  81868. // The object needs to be provided an url to a texture containing the color
  81869. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  81870. // Use an image editing software to tweak the LUT to match your needs.
  81871. //
  81872. // For an example of a color LUT, see here:
  81873. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  81874. // For explanations on color grading, see here:
  81875. // http://udn.epicgames.com/Three/ColorGrading.html
  81876. //
  81877. var BABYLON;
  81878. (function (BABYLON) {
  81879. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  81880. __extends(ColorCorrectionPostProcess, _super);
  81881. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  81882. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  81883. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81884. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  81885. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81886. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81887. _this.onApply = function (effect) {
  81888. effect.setTexture("colorTable", _this._colorTableTexture);
  81889. };
  81890. return _this;
  81891. }
  81892. return ColorCorrectionPostProcess;
  81893. }(BABYLON.PostProcess));
  81894. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  81895. })(BABYLON || (BABYLON = {}));
  81896. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  81897. var BABYLON;
  81898. (function (BABYLON) {
  81899. /** Defines operator used for tonemapping */
  81900. var TonemappingOperator;
  81901. (function (TonemappingOperator) {
  81902. /** Hable */
  81903. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  81904. /** Reinhard */
  81905. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  81906. /** HejiDawson */
  81907. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  81908. /** Photographic */
  81909. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  81910. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  81911. ;
  81912. /**
  81913. * Defines a post process to apply tone mapping
  81914. */
  81915. var TonemapPostProcess = /** @class */ (function (_super) {
  81916. __extends(TonemapPostProcess, _super);
  81917. /**
  81918. * Creates a new TonemapPostProcess
  81919. * @param name defines the name of the postprocess
  81920. * @param _operator defines the operator to use
  81921. * @param exposureAdjustment defines the required exposure adjustement
  81922. * @param camera defines the camera to use (can be null)
  81923. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  81924. * @param engine defines the hosting engine (can be ignore if camera is set)
  81925. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  81926. */
  81927. function TonemapPostProcess(name, _operator,
  81928. /** Defines the required exposure adjustement */
  81929. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  81930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81931. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81932. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  81933. _this._operator = _operator;
  81934. _this.exposureAdjustment = exposureAdjustment;
  81935. var defines = "#define ";
  81936. if (_this._operator === TonemappingOperator.Hable)
  81937. defines += "HABLE_TONEMAPPING";
  81938. else if (_this._operator === TonemappingOperator.Reinhard)
  81939. defines += "REINHARD_TONEMAPPING";
  81940. else if (_this._operator === TonemappingOperator.HejiDawson)
  81941. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  81942. else if (_this._operator === TonemappingOperator.Photographic)
  81943. defines += "PHOTOGRAPHIC_TONEMAPPING";
  81944. //sadly a second call to create the effect.
  81945. _this.updateEffect(defines);
  81946. _this.onApply = function (effect) {
  81947. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  81948. };
  81949. return _this;
  81950. }
  81951. return TonemapPostProcess;
  81952. }(BABYLON.PostProcess));
  81953. BABYLON.TonemapPostProcess = TonemapPostProcess;
  81954. })(BABYLON || (BABYLON = {}));
  81955. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  81956. var BABYLON;
  81957. (function (BABYLON) {
  81958. var DisplayPassPostProcess = /** @class */ (function (_super) {
  81959. __extends(DisplayPassPostProcess, _super);
  81960. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  81961. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  81962. }
  81963. return DisplayPassPostProcess;
  81964. }(BABYLON.PostProcess));
  81965. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  81966. })(BABYLON || (BABYLON = {}));
  81967. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  81968. var BABYLON;
  81969. (function (BABYLON) {
  81970. var HighlightsPostProcess = /** @class */ (function (_super) {
  81971. __extends(HighlightsPostProcess, _super);
  81972. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  81973. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81974. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81975. }
  81976. return HighlightsPostProcess;
  81977. }(BABYLON.PostProcess));
  81978. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  81979. })(BABYLON || (BABYLON = {}));
  81980. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  81981. var BABYLON;
  81982. (function (BABYLON) {
  81983. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  81984. __extends(ImageProcessingPostProcess, _super);
  81985. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  81986. if (camera === void 0) { camera = null; }
  81987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81988. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  81989. _this._fromLinearSpace = true;
  81990. /**
  81991. * Defines cache preventing GC.
  81992. */
  81993. _this._defines = {
  81994. IMAGEPROCESSING: false,
  81995. VIGNETTE: false,
  81996. VIGNETTEBLENDMODEMULTIPLY: false,
  81997. VIGNETTEBLENDMODEOPAQUE: false,
  81998. TONEMAPPING: false,
  81999. TONEMAPPING_ACES: false,
  82000. CONTRAST: false,
  82001. COLORCURVES: false,
  82002. COLORGRADING: false,
  82003. COLORGRADING3D: false,
  82004. FROMLINEARSPACE: false,
  82005. SAMPLER3DGREENDEPTH: false,
  82006. SAMPLER3DBGRMAP: false,
  82007. IMAGEPROCESSINGPOSTPROCESS: false,
  82008. EXPOSURE: false,
  82009. };
  82010. // Setup the configuration as forced by the constructor. This would then not force the
  82011. // scene materials output in linear space and let untouched the default forward pass.
  82012. if (imageProcessingConfiguration) {
  82013. imageProcessingConfiguration.applyByPostProcess = true;
  82014. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82015. // This will cause the shader to be compiled
  82016. _this.fromLinearSpace = false;
  82017. }
  82018. // Setup the default processing configuration to the scene.
  82019. else {
  82020. _this._attachImageProcessingConfiguration(null, true);
  82021. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82022. }
  82023. _this.onApply = function (effect) {
  82024. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82025. };
  82026. return _this;
  82027. }
  82028. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82029. /**
  82030. * Gets the image processing configuration used either in this material.
  82031. */
  82032. get: function () {
  82033. return this._imageProcessingConfiguration;
  82034. },
  82035. /**
  82036. * Sets the Default image processing configuration used either in the this material.
  82037. *
  82038. * If sets to null, the scene one is in use.
  82039. */
  82040. set: function (value) {
  82041. this._attachImageProcessingConfiguration(value);
  82042. },
  82043. enumerable: true,
  82044. configurable: true
  82045. });
  82046. /**
  82047. * Attaches a new image processing configuration to the PBR Material.
  82048. * @param configuration
  82049. */
  82050. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82051. var _this = this;
  82052. if (doNotBuild === void 0) { doNotBuild = false; }
  82053. if (configuration === this._imageProcessingConfiguration) {
  82054. return;
  82055. }
  82056. // Detaches observer.
  82057. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82058. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82059. }
  82060. // Pick the scene configuration if needed.
  82061. if (!configuration) {
  82062. var scene = null;
  82063. var engine = this.getEngine();
  82064. var camera = this.getCamera();
  82065. if (camera) {
  82066. scene = camera.getScene();
  82067. }
  82068. else if (engine && engine.scenes) {
  82069. var scenes = engine.scenes;
  82070. scene = scenes[scenes.length - 1];
  82071. }
  82072. else {
  82073. scene = BABYLON.Engine.LastCreatedScene;
  82074. }
  82075. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82076. }
  82077. else {
  82078. this._imageProcessingConfiguration = configuration;
  82079. }
  82080. // Attaches observer.
  82081. if (this._imageProcessingConfiguration) {
  82082. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82083. _this._updateParameters();
  82084. });
  82085. }
  82086. // Ensure the effect will be rebuilt.
  82087. if (!doNotBuild) {
  82088. this._updateParameters();
  82089. }
  82090. };
  82091. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  82092. /**
  82093. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82094. */
  82095. get: function () {
  82096. return this.imageProcessingConfiguration.colorCurves;
  82097. },
  82098. /**
  82099. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82100. */
  82101. set: function (value) {
  82102. this.imageProcessingConfiguration.colorCurves = value;
  82103. },
  82104. enumerable: true,
  82105. configurable: true
  82106. });
  82107. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  82108. /**
  82109. * Gets wether the color curves effect is enabled.
  82110. */
  82111. get: function () {
  82112. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82113. },
  82114. /**
  82115. * Sets wether the color curves effect is enabled.
  82116. */
  82117. set: function (value) {
  82118. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82119. },
  82120. enumerable: true,
  82121. configurable: true
  82122. });
  82123. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  82124. /**
  82125. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82126. */
  82127. get: function () {
  82128. return this.imageProcessingConfiguration.colorGradingTexture;
  82129. },
  82130. /**
  82131. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82132. */
  82133. set: function (value) {
  82134. this.imageProcessingConfiguration.colorGradingTexture = value;
  82135. },
  82136. enumerable: true,
  82137. configurable: true
  82138. });
  82139. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  82140. /**
  82141. * Gets wether the color grading effect is enabled.
  82142. */
  82143. get: function () {
  82144. return this.imageProcessingConfiguration.colorGradingEnabled;
  82145. },
  82146. /**
  82147. * Gets wether the color grading effect is enabled.
  82148. */
  82149. set: function (value) {
  82150. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82151. },
  82152. enumerable: true,
  82153. configurable: true
  82154. });
  82155. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  82156. /**
  82157. * Gets exposure used in the effect.
  82158. */
  82159. get: function () {
  82160. return this.imageProcessingConfiguration.exposure;
  82161. },
  82162. /**
  82163. * Sets exposure used in the effect.
  82164. */
  82165. set: function (value) {
  82166. this.imageProcessingConfiguration.exposure = value;
  82167. },
  82168. enumerable: true,
  82169. configurable: true
  82170. });
  82171. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  82172. /**
  82173. * Gets wether tonemapping is enabled or not.
  82174. */
  82175. get: function () {
  82176. return this._imageProcessingConfiguration.toneMappingEnabled;
  82177. },
  82178. /**
  82179. * Sets wether tonemapping is enabled or not
  82180. */
  82181. set: function (value) {
  82182. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82183. },
  82184. enumerable: true,
  82185. configurable: true
  82186. });
  82187. ;
  82188. ;
  82189. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  82190. /**
  82191. * Gets contrast used in the effect.
  82192. */
  82193. get: function () {
  82194. return this.imageProcessingConfiguration.contrast;
  82195. },
  82196. /**
  82197. * Sets contrast used in the effect.
  82198. */
  82199. set: function (value) {
  82200. this.imageProcessingConfiguration.contrast = value;
  82201. },
  82202. enumerable: true,
  82203. configurable: true
  82204. });
  82205. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  82206. /**
  82207. * Gets Vignette stretch size.
  82208. */
  82209. get: function () {
  82210. return this.imageProcessingConfiguration.vignetteStretch;
  82211. },
  82212. /**
  82213. * Sets Vignette stretch size.
  82214. */
  82215. set: function (value) {
  82216. this.imageProcessingConfiguration.vignetteStretch = value;
  82217. },
  82218. enumerable: true,
  82219. configurable: true
  82220. });
  82221. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  82222. /**
  82223. * Gets Vignette centre X Offset.
  82224. */
  82225. get: function () {
  82226. return this.imageProcessingConfiguration.vignetteCentreX;
  82227. },
  82228. /**
  82229. * Sets Vignette centre X Offset.
  82230. */
  82231. set: function (value) {
  82232. this.imageProcessingConfiguration.vignetteCentreX = value;
  82233. },
  82234. enumerable: true,
  82235. configurable: true
  82236. });
  82237. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  82238. /**
  82239. * Gets Vignette centre Y Offset.
  82240. */
  82241. get: function () {
  82242. return this.imageProcessingConfiguration.vignetteCentreY;
  82243. },
  82244. /**
  82245. * Sets Vignette centre Y Offset.
  82246. */
  82247. set: function (value) {
  82248. this.imageProcessingConfiguration.vignetteCentreY = value;
  82249. },
  82250. enumerable: true,
  82251. configurable: true
  82252. });
  82253. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82254. /**
  82255. * Gets Vignette weight or intensity of the vignette effect.
  82256. */
  82257. get: function () {
  82258. return this.imageProcessingConfiguration.vignetteWeight;
  82259. },
  82260. /**
  82261. * Sets Vignette weight or intensity of the vignette effect.
  82262. */
  82263. set: function (value) {
  82264. this.imageProcessingConfiguration.vignetteWeight = value;
  82265. },
  82266. enumerable: true,
  82267. configurable: true
  82268. });
  82269. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82270. /**
  82271. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82272. * if vignetteEnabled is set to true.
  82273. */
  82274. get: function () {
  82275. return this.imageProcessingConfiguration.vignetteColor;
  82276. },
  82277. /**
  82278. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82279. * if vignetteEnabled is set to true.
  82280. */
  82281. set: function (value) {
  82282. this.imageProcessingConfiguration.vignetteColor = value;
  82283. },
  82284. enumerable: true,
  82285. configurable: true
  82286. });
  82287. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82288. /**
  82289. * Gets Camera field of view used by the Vignette effect.
  82290. */
  82291. get: function () {
  82292. return this.imageProcessingConfiguration.vignetteCameraFov;
  82293. },
  82294. /**
  82295. * Sets Camera field of view used by the Vignette effect.
  82296. */
  82297. set: function (value) {
  82298. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82299. },
  82300. enumerable: true,
  82301. configurable: true
  82302. });
  82303. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82304. /**
  82305. * Gets the vignette blend mode allowing different kind of effect.
  82306. */
  82307. get: function () {
  82308. return this.imageProcessingConfiguration.vignetteBlendMode;
  82309. },
  82310. /**
  82311. * Sets the vignette blend mode allowing different kind of effect.
  82312. */
  82313. set: function (value) {
  82314. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82315. },
  82316. enumerable: true,
  82317. configurable: true
  82318. });
  82319. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82320. /**
  82321. * Gets wether the vignette effect is enabled.
  82322. */
  82323. get: function () {
  82324. return this.imageProcessingConfiguration.vignetteEnabled;
  82325. },
  82326. /**
  82327. * Sets wether the vignette effect is enabled.
  82328. */
  82329. set: function (value) {
  82330. this.imageProcessingConfiguration.vignetteEnabled = value;
  82331. },
  82332. enumerable: true,
  82333. configurable: true
  82334. });
  82335. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82336. /**
  82337. * Gets wether the input of the processing is in Gamma or Linear Space.
  82338. */
  82339. get: function () {
  82340. return this._fromLinearSpace;
  82341. },
  82342. /**
  82343. * Sets wether the input of the processing is in Gamma or Linear Space.
  82344. */
  82345. set: function (value) {
  82346. if (this._fromLinearSpace === value) {
  82347. return;
  82348. }
  82349. this._fromLinearSpace = value;
  82350. this._updateParameters();
  82351. },
  82352. enumerable: true,
  82353. configurable: true
  82354. });
  82355. ImageProcessingPostProcess.prototype.getClassName = function () {
  82356. return "ImageProcessingPostProcess";
  82357. };
  82358. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82359. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82360. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82361. var defines = "";
  82362. for (var define in this._defines) {
  82363. if (this._defines[define]) {
  82364. defines += "#define " + define + ";\r\n";
  82365. }
  82366. }
  82367. var samplers = ["textureSampler"];
  82368. var uniforms = ["scale"];
  82369. if (BABYLON.ImageProcessingConfiguration) {
  82370. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82371. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82372. }
  82373. this.updateEffect(defines, uniforms, samplers);
  82374. };
  82375. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82376. _super.prototype.dispose.call(this, camera);
  82377. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82378. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82379. }
  82380. if (this._imageProcessingConfiguration) {
  82381. this.imageProcessingConfiguration.applyByPostProcess = false;
  82382. }
  82383. };
  82384. __decorate([
  82385. BABYLON.serialize()
  82386. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82387. return ImageProcessingPostProcess;
  82388. }(BABYLON.PostProcess));
  82389. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82390. })(BABYLON || (BABYLON = {}));
  82391. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82392. var BABYLON;
  82393. (function (BABYLON) {
  82394. /**
  82395. * Class used to store bone information
  82396. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82397. */
  82398. var Bone = /** @class */ (function (_super) {
  82399. __extends(Bone, _super);
  82400. /**
  82401. * Create a new bone
  82402. * @param name defines the bone name
  82403. * @param skeleton defines the parent skeleton
  82404. * @param parentBone defines the parent (can be null if the bone is the root)
  82405. * @param localMatrix defines the local matrix
  82406. * @param restPose defines the rest pose matrix
  82407. * @param baseMatrix defines the base matrix
  82408. * @param index defines index of the bone in the hiearchy
  82409. */
  82410. function Bone(
  82411. /**
  82412. * defines the bone name
  82413. */
  82414. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82415. if (parentBone === void 0) { parentBone = null; }
  82416. if (localMatrix === void 0) { localMatrix = null; }
  82417. if (restPose === void 0) { restPose = null; }
  82418. if (baseMatrix === void 0) { baseMatrix = null; }
  82419. if (index === void 0) { index = null; }
  82420. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82421. _this.name = name;
  82422. /**
  82423. * Gets the list of child bones
  82424. */
  82425. _this.children = new Array();
  82426. /** Gets the animations associated with this bone */
  82427. _this.animations = new Array();
  82428. /**
  82429. * @hidden Internal only
  82430. * Set this value to map this bone to a different index in the transform matrices
  82431. * Set this value to -1 to exclude the bone from the transform matrices
  82432. */
  82433. _this._index = null;
  82434. _this._absoluteTransform = new BABYLON.Matrix();
  82435. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82436. _this._scalingDeterminant = 1;
  82437. _this._worldTransform = new BABYLON.Matrix();
  82438. _this._needToDecompose = true;
  82439. _this._needToCompose = false;
  82440. _this._skeleton = skeleton;
  82441. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82442. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82443. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82444. _this._index = index;
  82445. skeleton.bones.push(_this);
  82446. _this.setParent(parentBone, false);
  82447. if (baseMatrix || localMatrix) {
  82448. _this._updateDifferenceMatrix();
  82449. }
  82450. return _this;
  82451. }
  82452. Object.defineProperty(Bone.prototype, "_matrix", {
  82453. /** @hidden */
  82454. get: function () {
  82455. this._compose();
  82456. return this._localMatrix;
  82457. },
  82458. /** @hidden */
  82459. set: function (value) {
  82460. this._localMatrix.copyFrom(value);
  82461. this._needToDecompose = true;
  82462. },
  82463. enumerable: true,
  82464. configurable: true
  82465. });
  82466. // Members
  82467. /**
  82468. * Gets the parent skeleton
  82469. * @returns a skeleton
  82470. */
  82471. Bone.prototype.getSkeleton = function () {
  82472. return this._skeleton;
  82473. };
  82474. /**
  82475. * Gets parent bone
  82476. * @returns a bone or null if the bone is the root of the bone hierarchy
  82477. */
  82478. Bone.prototype.getParent = function () {
  82479. return this._parent;
  82480. };
  82481. /**
  82482. * Sets the parent bone
  82483. * @param parent defines the parent (can be null if the bone is the root)
  82484. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82485. */
  82486. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82487. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82488. if (this._parent === parent) {
  82489. return;
  82490. }
  82491. if (this._parent) {
  82492. var index = this._parent.children.indexOf(this);
  82493. if (index !== -1) {
  82494. this._parent.children.splice(index, 1);
  82495. }
  82496. }
  82497. this._parent = parent;
  82498. if (this._parent) {
  82499. this._parent.children.push(this);
  82500. }
  82501. if (updateDifferenceMatrix) {
  82502. this._updateDifferenceMatrix();
  82503. }
  82504. this.markAsDirty();
  82505. };
  82506. /**
  82507. * Gets the local matrix
  82508. * @returns a matrix
  82509. */
  82510. Bone.prototype.getLocalMatrix = function () {
  82511. this._compose();
  82512. return this._localMatrix;
  82513. };
  82514. /**
  82515. * Gets the base matrix (initial matrix which remains unchanged)
  82516. * @returns a matrix
  82517. */
  82518. Bone.prototype.getBaseMatrix = function () {
  82519. return this._baseMatrix;
  82520. };
  82521. /**
  82522. * Gets the rest pose matrix
  82523. * @returns a matrix
  82524. */
  82525. Bone.prototype.getRestPose = function () {
  82526. return this._restPose;
  82527. };
  82528. /**
  82529. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  82530. */
  82531. Bone.prototype.getWorldMatrix = function () {
  82532. return this._worldTransform;
  82533. };
  82534. /**
  82535. * Sets the local matrix to rest pose matrix
  82536. */
  82537. Bone.prototype.returnToRest = function () {
  82538. this.updateMatrix(this._restPose.clone());
  82539. };
  82540. /**
  82541. * Gets the inverse of the absolute transform matrix.
  82542. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  82543. * @returns a matrix
  82544. */
  82545. Bone.prototype.getInvertedAbsoluteTransform = function () {
  82546. return this._invertedAbsoluteTransform;
  82547. };
  82548. /**
  82549. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  82550. * @returns a matrix
  82551. */
  82552. Bone.prototype.getAbsoluteTransform = function () {
  82553. return this._absoluteTransform;
  82554. };
  82555. Object.defineProperty(Bone.prototype, "position", {
  82556. // Properties (matches AbstractMesh properties)
  82557. /** Gets or sets current position (in local space) */
  82558. get: function () {
  82559. this._decompose();
  82560. return this._localPosition;
  82561. },
  82562. set: function (newPosition) {
  82563. this._decompose();
  82564. this._localPosition.copyFrom(newPosition);
  82565. this._markAsDirtyAndCompose();
  82566. },
  82567. enumerable: true,
  82568. configurable: true
  82569. });
  82570. Object.defineProperty(Bone.prototype, "rotation", {
  82571. /** Gets or sets current rotation (in local space) */
  82572. get: function () {
  82573. return this.getRotation();
  82574. },
  82575. set: function (newRotation) {
  82576. this.setRotation(newRotation);
  82577. },
  82578. enumerable: true,
  82579. configurable: true
  82580. });
  82581. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  82582. /** Gets or sets current rotation quaternion (in local space) */
  82583. get: function () {
  82584. this._decompose();
  82585. return this._localRotation;
  82586. },
  82587. set: function (newRotation) {
  82588. this.setRotationQuaternion(newRotation);
  82589. },
  82590. enumerable: true,
  82591. configurable: true
  82592. });
  82593. Object.defineProperty(Bone.prototype, "scaling", {
  82594. /** Gets or sets current scaling (in local space) */
  82595. get: function () {
  82596. return this.getScale();
  82597. },
  82598. set: function (newScaling) {
  82599. this.setScale(newScaling);
  82600. },
  82601. enumerable: true,
  82602. configurable: true
  82603. });
  82604. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  82605. /**
  82606. * Gets the animation properties override
  82607. */
  82608. get: function () {
  82609. return this._skeleton.animationPropertiesOverride;
  82610. },
  82611. enumerable: true,
  82612. configurable: true
  82613. });
  82614. // Methods
  82615. Bone.prototype._decompose = function () {
  82616. if (!this._needToDecompose) {
  82617. return;
  82618. }
  82619. this._needToDecompose = false;
  82620. if (!this._localScaling) {
  82621. this._localScaling = BABYLON.Vector3.Zero();
  82622. this._localRotation = BABYLON.Quaternion.Zero();
  82623. this._localPosition = BABYLON.Vector3.Zero();
  82624. }
  82625. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  82626. };
  82627. Bone.prototype._compose = function () {
  82628. if (!this._needToCompose) {
  82629. return;
  82630. }
  82631. this._needToCompose = false;
  82632. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  82633. };
  82634. /**
  82635. * Update the base and local matrices
  82636. * @param matrix defines the new base or local matrix
  82637. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82638. * @param updateLocalMatrix defines if the local matrix should be updated
  82639. */
  82640. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  82641. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82642. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  82643. this._baseMatrix.copyFrom(matrix);
  82644. if (updateDifferenceMatrix) {
  82645. this._updateDifferenceMatrix();
  82646. }
  82647. if (updateLocalMatrix) {
  82648. this._localMatrix.copyFrom(matrix);
  82649. this._markAsDirtyAndDecompose();
  82650. }
  82651. else {
  82652. this.markAsDirty();
  82653. }
  82654. };
  82655. /** @hidden */
  82656. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  82657. if (updateChildren === void 0) { updateChildren = true; }
  82658. if (!rootMatrix) {
  82659. rootMatrix = this._baseMatrix;
  82660. }
  82661. if (this._parent) {
  82662. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82663. }
  82664. else {
  82665. this._absoluteTransform.copyFrom(rootMatrix);
  82666. }
  82667. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  82668. if (updateChildren) {
  82669. for (var index = 0; index < this.children.length; index++) {
  82670. this.children[index]._updateDifferenceMatrix();
  82671. }
  82672. }
  82673. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  82674. };
  82675. /**
  82676. * Flag the bone as dirty (Forcing it to update everything)
  82677. */
  82678. Bone.prototype.markAsDirty = function () {
  82679. this._currentRenderId++;
  82680. this._childRenderId++;
  82681. this._skeleton._markAsDirty();
  82682. };
  82683. Bone.prototype._markAsDirtyAndCompose = function () {
  82684. this.markAsDirty();
  82685. this._needToCompose = true;
  82686. };
  82687. Bone.prototype._markAsDirtyAndDecompose = function () {
  82688. this.markAsDirty();
  82689. this._needToDecompose = true;
  82690. };
  82691. /**
  82692. * Copy an animation range from another bone
  82693. * @param source defines the source bone
  82694. * @param rangeName defines the range name to copy
  82695. * @param frameOffset defines the frame offset
  82696. * @param rescaleAsRequired defines if rescaling must be applied if required
  82697. * @param skelDimensionsRatio defines the scaling ratio
  82698. * @returns true if operation was successful
  82699. */
  82700. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  82701. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82702. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  82703. // all animation may be coming from a library skeleton, so may need to create animation
  82704. if (this.animations.length === 0) {
  82705. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  82706. this.animations[0].setKeys([]);
  82707. }
  82708. // get animation info / verify there is such a range from the source bone
  82709. var sourceRange = source.animations[0].getRange(rangeName);
  82710. if (!sourceRange) {
  82711. return false;
  82712. }
  82713. var from = sourceRange.from;
  82714. var to = sourceRange.to;
  82715. var sourceKeys = source.animations[0].getKeys();
  82716. // rescaling prep
  82717. var sourceBoneLength = source.length;
  82718. var sourceParent = source.getParent();
  82719. var parent = this.getParent();
  82720. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  82721. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  82722. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  82723. var destKeys = this.animations[0].getKeys();
  82724. // loop vars declaration
  82725. var orig;
  82726. var origTranslation;
  82727. var mat;
  82728. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  82729. orig = sourceKeys[key];
  82730. if (orig.frame >= from && orig.frame <= to) {
  82731. if (rescaleAsRequired) {
  82732. mat = orig.value.clone();
  82733. // scale based on parent ratio, when bone has parent
  82734. if (parentScalingReqd) {
  82735. origTranslation = mat.getTranslation();
  82736. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  82737. // scale based on skeleton dimension ratio when root bone, and value is passed
  82738. }
  82739. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  82740. origTranslation = mat.getTranslation();
  82741. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  82742. // use original when root bone, and no data for skelDimensionsRatio
  82743. }
  82744. else {
  82745. mat = orig.value;
  82746. }
  82747. }
  82748. else {
  82749. mat = orig.value;
  82750. }
  82751. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  82752. }
  82753. }
  82754. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  82755. return true;
  82756. };
  82757. /**
  82758. * Translate the bone in local or world space
  82759. * @param vec The amount to translate the bone
  82760. * @param space The space that the translation is in
  82761. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82762. */
  82763. Bone.prototype.translate = function (vec, space, mesh) {
  82764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82765. var lm = this.getLocalMatrix();
  82766. if (space == BABYLON.Space.LOCAL) {
  82767. lm.m[12] += vec.x;
  82768. lm.m[13] += vec.y;
  82769. lm.m[14] += vec.z;
  82770. }
  82771. else {
  82772. var wm = null;
  82773. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82774. if (mesh) {
  82775. wm = mesh.getWorldMatrix();
  82776. }
  82777. this._skeleton.computeAbsoluteTransforms();
  82778. var tmat = Bone._tmpMats[0];
  82779. var tvec = Bone._tmpVecs[0];
  82780. if (this._parent) {
  82781. if (mesh && wm) {
  82782. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82783. tmat.multiplyToRef(wm, tmat);
  82784. }
  82785. else {
  82786. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82787. }
  82788. }
  82789. tmat.m[12] = 0;
  82790. tmat.m[13] = 0;
  82791. tmat.m[14] = 0;
  82792. tmat.invert();
  82793. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  82794. lm.m[12] += tvec.x;
  82795. lm.m[13] += tvec.y;
  82796. lm.m[14] += tvec.z;
  82797. }
  82798. this._markAsDirtyAndDecompose();
  82799. };
  82800. /**
  82801. * Set the postion of the bone in local or world space
  82802. * @param position The position to set the bone
  82803. * @param space The space that the position is in
  82804. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82805. */
  82806. Bone.prototype.setPosition = function (position, space, mesh) {
  82807. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82808. var lm = this.getLocalMatrix();
  82809. if (space == BABYLON.Space.LOCAL) {
  82810. lm.m[12] = position.x;
  82811. lm.m[13] = position.y;
  82812. lm.m[14] = position.z;
  82813. }
  82814. else {
  82815. var wm = null;
  82816. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82817. if (mesh) {
  82818. wm = mesh.getWorldMatrix();
  82819. }
  82820. this._skeleton.computeAbsoluteTransforms();
  82821. var tmat = Bone._tmpMats[0];
  82822. var vec = Bone._tmpVecs[0];
  82823. if (this._parent) {
  82824. if (mesh && wm) {
  82825. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82826. tmat.multiplyToRef(wm, tmat);
  82827. }
  82828. else {
  82829. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82830. }
  82831. }
  82832. tmat.invert();
  82833. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  82834. lm.m[12] = vec.x;
  82835. lm.m[13] = vec.y;
  82836. lm.m[14] = vec.z;
  82837. }
  82838. this._markAsDirtyAndDecompose();
  82839. };
  82840. /**
  82841. * Set the absolute position of the bone (world space)
  82842. * @param position The position to set the bone
  82843. * @param mesh The mesh that this bone is attached to
  82844. */
  82845. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  82846. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  82847. };
  82848. /**
  82849. * Scale the bone on the x, y and z axes (in local space)
  82850. * @param x The amount to scale the bone on the x axis
  82851. * @param y The amount to scale the bone on the y axis
  82852. * @param z The amount to scale the bone on the z axis
  82853. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  82854. */
  82855. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  82856. if (scaleChildren === void 0) { scaleChildren = false; }
  82857. var locMat = this.getLocalMatrix();
  82858. // Apply new scaling on top of current local matrix
  82859. var scaleMat = Bone._tmpMats[0];
  82860. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  82861. scaleMat.multiplyToRef(locMat, locMat);
  82862. // Invert scaling matrix and apply the inverse to all children
  82863. scaleMat.invert();
  82864. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  82865. var child = _a[_i];
  82866. var cm = child.getLocalMatrix();
  82867. cm.multiplyToRef(scaleMat, cm);
  82868. cm.m[12] *= x;
  82869. cm.m[13] *= y;
  82870. cm.m[14] *= z;
  82871. child._markAsDirtyAndDecompose();
  82872. }
  82873. this._markAsDirtyAndDecompose();
  82874. if (scaleChildren) {
  82875. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  82876. var child = _c[_b];
  82877. child.scale(x, y, z, scaleChildren);
  82878. }
  82879. }
  82880. };
  82881. /**
  82882. * Set the bone scaling in local space
  82883. * @param scale defines the scaling vector
  82884. */
  82885. Bone.prototype.setScale = function (scale) {
  82886. this._decompose();
  82887. this._localScaling.copyFrom(scale);
  82888. this._markAsDirtyAndCompose();
  82889. };
  82890. /**
  82891. * Gets the current scaling in local space
  82892. * @returns the current scaling vector
  82893. */
  82894. Bone.prototype.getScale = function () {
  82895. this._decompose();
  82896. return this._localScaling;
  82897. };
  82898. /**
  82899. * Gets the current scaling in local space and stores it in a target vector
  82900. * @param result defines the target vector
  82901. */
  82902. Bone.prototype.getScaleToRef = function (result) {
  82903. this._decompose();
  82904. result.copyFrom(this._localScaling);
  82905. };
  82906. /**
  82907. * Set the yaw, pitch, and roll of the bone in local or world space
  82908. * @param yaw The rotation of the bone on the y axis
  82909. * @param pitch The rotation of the bone on the x axis
  82910. * @param roll The rotation of the bone on the z axis
  82911. * @param space The space that the axes of rotation are in
  82912. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82913. */
  82914. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  82915. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82916. if (space === BABYLON.Space.LOCAL) {
  82917. var quat = Bone._tmpQuat;
  82918. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  82919. this.setRotationQuaternion(quat, space, mesh);
  82920. return;
  82921. }
  82922. var rotMatInv = Bone._tmpMats[0];
  82923. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82924. return;
  82925. }
  82926. var rotMat = Bone._tmpMats[1];
  82927. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  82928. rotMatInv.multiplyToRef(rotMat, rotMat);
  82929. this._rotateWithMatrix(rotMat, space, mesh);
  82930. };
  82931. /**
  82932. * Add a rotation to the bone on an axis in local or world space
  82933. * @param axis The axis to rotate the bone on
  82934. * @param amount The amount to rotate the bone
  82935. * @param space The space that the axis is in
  82936. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82937. */
  82938. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  82939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82940. var rmat = Bone._tmpMats[0];
  82941. rmat.m[12] = 0;
  82942. rmat.m[13] = 0;
  82943. rmat.m[14] = 0;
  82944. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  82945. this._rotateWithMatrix(rmat, space, mesh);
  82946. };
  82947. /**
  82948. * Set the rotation of the bone to a particular axis angle in local or world space
  82949. * @param axis The axis to rotate the bone on
  82950. * @param angle The angle that the bone should be rotated to
  82951. * @param space The space that the axis is in
  82952. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82953. */
  82954. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  82955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82956. if (space === BABYLON.Space.LOCAL) {
  82957. var quat = Bone._tmpQuat;
  82958. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  82959. this.setRotationQuaternion(quat, space, mesh);
  82960. return;
  82961. }
  82962. var rotMatInv = Bone._tmpMats[0];
  82963. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82964. return;
  82965. }
  82966. var rotMat = Bone._tmpMats[1];
  82967. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  82968. rotMatInv.multiplyToRef(rotMat, rotMat);
  82969. this._rotateWithMatrix(rotMat, space, mesh);
  82970. };
  82971. /**
  82972. * Set the euler rotation of the bone in local of world space
  82973. * @param rotation The euler rotation that the bone should be set to
  82974. * @param space The space that the rotation is in
  82975. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82976. */
  82977. Bone.prototype.setRotation = function (rotation, space, mesh) {
  82978. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82979. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  82980. };
  82981. /**
  82982. * Set the quaternion rotation of the bone in local of world space
  82983. * @param quat The quaternion rotation that the bone should be set to
  82984. * @param space The space that the rotation is in
  82985. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82986. */
  82987. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  82988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82989. if (space === BABYLON.Space.LOCAL) {
  82990. this._decompose();
  82991. this._localRotation.copyFrom(quat);
  82992. this._markAsDirtyAndCompose();
  82993. return;
  82994. }
  82995. var rotMatInv = Bone._tmpMats[0];
  82996. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82997. return;
  82998. }
  82999. var rotMat = Bone._tmpMats[1];
  83000. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83001. rotMatInv.multiplyToRef(rotMat, rotMat);
  83002. this._rotateWithMatrix(rotMat, space, mesh);
  83003. };
  83004. /**
  83005. * Set the rotation matrix of the bone in local of world space
  83006. * @param rotMat The rotation matrix that the bone should be set to
  83007. * @param space The space that the rotation is in
  83008. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83009. */
  83010. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83012. if (space === BABYLON.Space.LOCAL) {
  83013. var quat = Bone._tmpQuat;
  83014. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83015. this.setRotationQuaternion(quat, space, mesh);
  83016. return;
  83017. }
  83018. var rotMatInv = Bone._tmpMats[0];
  83019. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83020. return;
  83021. }
  83022. var rotMat2 = Bone._tmpMats[1];
  83023. rotMat2.copyFrom(rotMat);
  83024. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83025. this._rotateWithMatrix(rotMat2, space, mesh);
  83026. };
  83027. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83028. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83029. var lmat = this.getLocalMatrix();
  83030. var lx = lmat.m[12];
  83031. var ly = lmat.m[13];
  83032. var lz = lmat.m[14];
  83033. var parent = this.getParent();
  83034. var parentScale = Bone._tmpMats[3];
  83035. var parentScaleInv = Bone._tmpMats[4];
  83036. if (parent && space == BABYLON.Space.WORLD) {
  83037. if (mesh) {
  83038. parentScale.copyFrom(mesh.getWorldMatrix());
  83039. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83040. }
  83041. else {
  83042. parentScale.copyFrom(parent.getAbsoluteTransform());
  83043. }
  83044. parentScaleInv.copyFrom(parentScale);
  83045. parentScaleInv.invert();
  83046. lmat.multiplyToRef(parentScale, lmat);
  83047. lmat.multiplyToRef(rmat, lmat);
  83048. lmat.multiplyToRef(parentScaleInv, lmat);
  83049. }
  83050. else {
  83051. if (space == BABYLON.Space.WORLD && mesh) {
  83052. parentScale.copyFrom(mesh.getWorldMatrix());
  83053. parentScaleInv.copyFrom(parentScale);
  83054. parentScaleInv.invert();
  83055. lmat.multiplyToRef(parentScale, lmat);
  83056. lmat.multiplyToRef(rmat, lmat);
  83057. lmat.multiplyToRef(parentScaleInv, lmat);
  83058. }
  83059. else {
  83060. lmat.multiplyToRef(rmat, lmat);
  83061. }
  83062. }
  83063. lmat.m[12] = lx;
  83064. lmat.m[13] = ly;
  83065. lmat.m[14] = lz;
  83066. this.computeAbsoluteTransforms();
  83067. this._markAsDirtyAndDecompose();
  83068. };
  83069. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83070. var scaleMatrix = Bone._tmpMats[2];
  83071. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83072. if (mesh) {
  83073. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83074. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83075. }
  83076. rotMatInv.invert();
  83077. if (isNaN(rotMatInv.m[0])) {
  83078. // Matrix failed to invert.
  83079. // This can happen if scale is zero for example.
  83080. return false;
  83081. }
  83082. scaleMatrix.m[0] *= this._scalingDeterminant;
  83083. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83084. return true;
  83085. };
  83086. /**
  83087. * Get the position of the bone in local or world space
  83088. * @param space The space that the returned position is in
  83089. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83090. * @returns The position of the bone
  83091. */
  83092. Bone.prototype.getPosition = function (space, mesh) {
  83093. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83094. if (mesh === void 0) { mesh = null; }
  83095. var pos = BABYLON.Vector3.Zero();
  83096. this.getPositionToRef(space, mesh, pos);
  83097. return pos;
  83098. };
  83099. /**
  83100. * Copy the position of the bone to a vector3 in local or world space
  83101. * @param space The space that the returned position is in
  83102. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83103. * @param result The vector3 to copy the position to
  83104. */
  83105. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  83106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83107. if (space == BABYLON.Space.LOCAL) {
  83108. var lm = this.getLocalMatrix();
  83109. result.x = lm.m[12];
  83110. result.y = lm.m[13];
  83111. result.z = lm.m[14];
  83112. }
  83113. else {
  83114. var wm = null;
  83115. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83116. if (mesh) {
  83117. wm = mesh.getWorldMatrix();
  83118. }
  83119. this._skeleton.computeAbsoluteTransforms();
  83120. var tmat = Bone._tmpMats[0];
  83121. if (mesh && wm) {
  83122. tmat.copyFrom(this.getAbsoluteTransform());
  83123. tmat.multiplyToRef(wm, tmat);
  83124. }
  83125. else {
  83126. tmat = this.getAbsoluteTransform();
  83127. }
  83128. result.x = tmat.m[12];
  83129. result.y = tmat.m[13];
  83130. result.z = tmat.m[14];
  83131. }
  83132. };
  83133. /**
  83134. * Get the absolute position of the bone (world space)
  83135. * @param mesh The mesh that this bone is attached to
  83136. * @returns The absolute position of the bone
  83137. */
  83138. Bone.prototype.getAbsolutePosition = function (mesh) {
  83139. if (mesh === void 0) { mesh = null; }
  83140. var pos = BABYLON.Vector3.Zero();
  83141. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  83142. return pos;
  83143. };
  83144. /**
  83145. * Copy the absolute position of the bone (world space) to the result param
  83146. * @param mesh The mesh that this bone is attached to
  83147. * @param result The vector3 to copy the absolute position to
  83148. */
  83149. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  83150. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  83151. };
  83152. /**
  83153. * Compute the absolute transforms of this bone and its children
  83154. */
  83155. Bone.prototype.computeAbsoluteTransforms = function () {
  83156. this._compose();
  83157. if (this._parent) {
  83158. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83159. }
  83160. else {
  83161. this._absoluteTransform.copyFrom(this._localMatrix);
  83162. var poseMatrix = this._skeleton.getPoseMatrix();
  83163. if (poseMatrix) {
  83164. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  83165. }
  83166. }
  83167. var children = this.children;
  83168. var len = children.length;
  83169. for (var i = 0; i < len; i++) {
  83170. children[i].computeAbsoluteTransforms();
  83171. }
  83172. };
  83173. /**
  83174. * Get the world direction from an axis that is in the local space of the bone
  83175. * @param localAxis The local direction that is used to compute the world direction
  83176. * @param mesh The mesh that this bone is attached to
  83177. * @returns The world direction
  83178. */
  83179. Bone.prototype.getDirection = function (localAxis, mesh) {
  83180. if (mesh === void 0) { mesh = null; }
  83181. var result = BABYLON.Vector3.Zero();
  83182. this.getDirectionToRef(localAxis, mesh, result);
  83183. return result;
  83184. };
  83185. /**
  83186. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  83187. * @param localAxis The local direction that is used to compute the world direction
  83188. * @param mesh The mesh that this bone is attached to
  83189. * @param result The vector3 that the world direction will be copied to
  83190. */
  83191. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  83192. if (mesh === void 0) { mesh = null; }
  83193. var wm = null;
  83194. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83195. if (mesh) {
  83196. wm = mesh.getWorldMatrix();
  83197. }
  83198. this._skeleton.computeAbsoluteTransforms();
  83199. var mat = Bone._tmpMats[0];
  83200. mat.copyFrom(this.getAbsoluteTransform());
  83201. if (mesh && wm) {
  83202. mat.multiplyToRef(wm, mat);
  83203. }
  83204. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  83205. result.normalize();
  83206. };
  83207. /**
  83208. * Get the euler rotation of the bone in local or world space
  83209. * @param space The space that the rotation should be in
  83210. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83211. * @returns The euler rotation
  83212. */
  83213. Bone.prototype.getRotation = function (space, mesh) {
  83214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83215. if (mesh === void 0) { mesh = null; }
  83216. var result = BABYLON.Vector3.Zero();
  83217. this.getRotationToRef(space, mesh, result);
  83218. return result;
  83219. };
  83220. /**
  83221. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  83222. * @param space The space that the rotation should be in
  83223. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83224. * @param result The vector3 that the rotation should be copied to
  83225. */
  83226. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  83227. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83228. if (mesh === void 0) { mesh = null; }
  83229. var quat = Bone._tmpQuat;
  83230. this.getRotationQuaternionToRef(space, mesh, quat);
  83231. quat.toEulerAnglesToRef(result);
  83232. };
  83233. /**
  83234. * Get the quaternion rotation of the bone in either local or world space
  83235. * @param space The space that the rotation should be in
  83236. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83237. * @returns The quaternion rotation
  83238. */
  83239. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  83240. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83241. if (mesh === void 0) { mesh = null; }
  83242. var result = BABYLON.Quaternion.Identity();
  83243. this.getRotationQuaternionToRef(space, mesh, result);
  83244. return result;
  83245. };
  83246. /**
  83247. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83248. * @param space The space that the rotation should be in
  83249. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83250. * @param result The quaternion that the rotation should be copied to
  83251. */
  83252. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83253. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83254. if (mesh === void 0) { mesh = null; }
  83255. if (space == BABYLON.Space.LOCAL) {
  83256. this._decompose();
  83257. result.copyFrom(this._localRotation);
  83258. }
  83259. else {
  83260. var mat = Bone._tmpMats[0];
  83261. var amat = this.getAbsoluteTransform();
  83262. if (mesh) {
  83263. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83264. }
  83265. else {
  83266. mat.copyFrom(amat);
  83267. }
  83268. mat.m[0] *= this._scalingDeterminant;
  83269. mat.m[1] *= this._scalingDeterminant;
  83270. mat.m[2] *= this._scalingDeterminant;
  83271. mat.decompose(undefined, result, undefined);
  83272. }
  83273. };
  83274. /**
  83275. * Get the rotation matrix of the bone in local or world space
  83276. * @param space The space that the rotation should be in
  83277. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83278. * @returns The rotation matrix
  83279. */
  83280. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83281. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83282. var result = BABYLON.Matrix.Identity();
  83283. this.getRotationMatrixToRef(space, mesh, result);
  83284. return result;
  83285. };
  83286. /**
  83287. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83288. * @param space The space that the rotation should be in
  83289. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83290. * @param result The quaternion that the rotation should be copied to
  83291. */
  83292. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83294. if (space == BABYLON.Space.LOCAL) {
  83295. this.getLocalMatrix().getRotationMatrixToRef(result);
  83296. }
  83297. else {
  83298. var mat = Bone._tmpMats[0];
  83299. var amat = this.getAbsoluteTransform();
  83300. if (mesh) {
  83301. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83302. }
  83303. else {
  83304. mat.copyFrom(amat);
  83305. }
  83306. mat.m[0] *= this._scalingDeterminant;
  83307. mat.m[1] *= this._scalingDeterminant;
  83308. mat.m[2] *= this._scalingDeterminant;
  83309. mat.getRotationMatrixToRef(result);
  83310. }
  83311. };
  83312. /**
  83313. * Get the world position of a point that is in the local space of the bone
  83314. * @param position The local position
  83315. * @param mesh The mesh that this bone is attached to
  83316. * @returns The world position
  83317. */
  83318. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83319. if (mesh === void 0) { mesh = null; }
  83320. var result = BABYLON.Vector3.Zero();
  83321. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83322. return result;
  83323. };
  83324. /**
  83325. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83326. * @param position The local position
  83327. * @param mesh The mesh that this bone is attached to
  83328. * @param result The vector3 that the world position should be copied to
  83329. */
  83330. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83331. if (mesh === void 0) { mesh = null; }
  83332. var wm = null;
  83333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83334. if (mesh) {
  83335. wm = mesh.getWorldMatrix();
  83336. }
  83337. this._skeleton.computeAbsoluteTransforms();
  83338. var tmat = Bone._tmpMats[0];
  83339. if (mesh && wm) {
  83340. tmat.copyFrom(this.getAbsoluteTransform());
  83341. tmat.multiplyToRef(wm, tmat);
  83342. }
  83343. else {
  83344. tmat = this.getAbsoluteTransform();
  83345. }
  83346. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83347. };
  83348. /**
  83349. * Get the local position of a point that is in world space
  83350. * @param position The world position
  83351. * @param mesh The mesh that this bone is attached to
  83352. * @returns The local position
  83353. */
  83354. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83355. if (mesh === void 0) { mesh = null; }
  83356. var result = BABYLON.Vector3.Zero();
  83357. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83358. return result;
  83359. };
  83360. /**
  83361. * Get the local position of a point that is in world space and copy it to the result param
  83362. * @param position The world position
  83363. * @param mesh The mesh that this bone is attached to
  83364. * @param result The vector3 that the local position should be copied to
  83365. */
  83366. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83367. if (mesh === void 0) { mesh = null; }
  83368. var wm = null;
  83369. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83370. if (mesh) {
  83371. wm = mesh.getWorldMatrix();
  83372. }
  83373. this._skeleton.computeAbsoluteTransforms();
  83374. var tmat = Bone._tmpMats[0];
  83375. tmat.copyFrom(this.getAbsoluteTransform());
  83376. if (mesh && wm) {
  83377. tmat.multiplyToRef(wm, tmat);
  83378. }
  83379. tmat.invert();
  83380. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83381. };
  83382. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83383. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83384. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83385. return Bone;
  83386. }(BABYLON.Node));
  83387. BABYLON.Bone = Bone;
  83388. })(BABYLON || (BABYLON = {}));
  83389. //# sourceMappingURL=babylon.bone.js.map
  83390. var BABYLON;
  83391. (function (BABYLON) {
  83392. /**
  83393. * Class used to apply inverse kinematics to bones
  83394. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83395. */
  83396. var BoneIKController = /** @class */ (function () {
  83397. /**
  83398. * Creates a new BoneIKController
  83399. * @param mesh defines the mesh to control
  83400. * @param bone defines the bone to control
  83401. * @param options defines options to set up the controller
  83402. */
  83403. function BoneIKController(mesh, bone, options) {
  83404. /**
  83405. * Gets or sets the target position
  83406. */
  83407. this.targetPosition = BABYLON.Vector3.Zero();
  83408. /**
  83409. * Gets or sets the pole target position
  83410. */
  83411. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83412. /**
  83413. * Gets or sets the pole target local offset
  83414. */
  83415. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83416. /**
  83417. * Gets or sets the pole angle
  83418. */
  83419. this.poleAngle = 0;
  83420. /**
  83421. * 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)
  83422. */
  83423. this.slerpAmount = 1;
  83424. this._bone1Quat = BABYLON.Quaternion.Identity();
  83425. this._bone1Mat = BABYLON.Matrix.Identity();
  83426. this._bone2Ang = Math.PI;
  83427. this._maxAngle = Math.PI;
  83428. this._rightHandedSystem = false;
  83429. this._bendAxis = BABYLON.Vector3.Right();
  83430. this._slerping = false;
  83431. this._adjustRoll = 0;
  83432. this._bone2 = bone;
  83433. this._bone1 = bone.getParent();
  83434. if (!this._bone1) {
  83435. return;
  83436. }
  83437. this.mesh = mesh;
  83438. var bonePos = bone.getPosition();
  83439. if (bone.getAbsoluteTransform().determinant() > 0) {
  83440. this._rightHandedSystem = true;
  83441. this._bendAxis.x = 0;
  83442. this._bendAxis.y = 0;
  83443. this._bendAxis.z = -1;
  83444. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83445. this._adjustRoll = Math.PI * .5;
  83446. this._bendAxis.z = 1;
  83447. }
  83448. }
  83449. if (this._bone1.length) {
  83450. var boneScale1 = this._bone1.getScale();
  83451. var boneScale2 = this._bone2.getScale();
  83452. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83453. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83454. }
  83455. else if (this._bone1.children[0]) {
  83456. mesh.computeWorldMatrix(true);
  83457. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83458. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83459. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83460. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83461. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83462. }
  83463. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83464. this.maxAngle = Math.PI;
  83465. if (options) {
  83466. if (options.targetMesh) {
  83467. this.targetMesh = options.targetMesh;
  83468. this.targetMesh.computeWorldMatrix(true);
  83469. }
  83470. if (options.poleTargetMesh) {
  83471. this.poleTargetMesh = options.poleTargetMesh;
  83472. this.poleTargetMesh.computeWorldMatrix(true);
  83473. }
  83474. else if (options.poleTargetBone) {
  83475. this.poleTargetBone = options.poleTargetBone;
  83476. }
  83477. else if (this._bone1.getParent()) {
  83478. this.poleTargetBone = this._bone1.getParent();
  83479. }
  83480. if (options.poleTargetLocalOffset) {
  83481. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83482. }
  83483. if (options.poleAngle) {
  83484. this.poleAngle = options.poleAngle;
  83485. }
  83486. if (options.bendAxis) {
  83487. this._bendAxis.copyFrom(options.bendAxis);
  83488. }
  83489. if (options.maxAngle) {
  83490. this.maxAngle = options.maxAngle;
  83491. }
  83492. if (options.slerpAmount) {
  83493. this.slerpAmount = options.slerpAmount;
  83494. }
  83495. }
  83496. }
  83497. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83498. /**
  83499. * Gets or sets maximum allowed angle
  83500. */
  83501. get: function () {
  83502. return this._maxAngle;
  83503. },
  83504. set: function (value) {
  83505. this._setMaxAngle(value);
  83506. },
  83507. enumerable: true,
  83508. configurable: true
  83509. });
  83510. BoneIKController.prototype._setMaxAngle = function (ang) {
  83511. if (ang < 0) {
  83512. ang = 0;
  83513. }
  83514. if (ang > Math.PI || ang == undefined) {
  83515. ang = Math.PI;
  83516. }
  83517. this._maxAngle = ang;
  83518. var a = this._bone1Length;
  83519. var b = this._bone2Length;
  83520. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  83521. };
  83522. /**
  83523. * Force the controller to update the bones
  83524. */
  83525. BoneIKController.prototype.update = function () {
  83526. var bone1 = this._bone1;
  83527. if (!bone1) {
  83528. return;
  83529. }
  83530. var target = this.targetPosition;
  83531. var poleTarget = this.poleTargetPosition;
  83532. var mat1 = BoneIKController._tmpMats[0];
  83533. var mat2 = BoneIKController._tmpMats[1];
  83534. if (this.targetMesh) {
  83535. target.copyFrom(this.targetMesh.getAbsolutePosition());
  83536. }
  83537. if (this.poleTargetBone) {
  83538. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  83539. }
  83540. else if (this.poleTargetMesh) {
  83541. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  83542. }
  83543. var bonePos = BoneIKController._tmpVecs[0];
  83544. var zaxis = BoneIKController._tmpVecs[1];
  83545. var xaxis = BoneIKController._tmpVecs[2];
  83546. var yaxis = BoneIKController._tmpVecs[3];
  83547. var upAxis = BoneIKController._tmpVecs[4];
  83548. var _tmpQuat = BoneIKController._tmpQuat;
  83549. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  83550. poleTarget.subtractToRef(bonePos, upAxis);
  83551. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  83552. upAxis.y = 1;
  83553. }
  83554. else {
  83555. upAxis.normalize();
  83556. }
  83557. target.subtractToRef(bonePos, yaxis);
  83558. yaxis.normalize();
  83559. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  83560. zaxis.normalize();
  83561. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  83562. xaxis.normalize();
  83563. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  83564. var a = this._bone1Length;
  83565. var b = this._bone2Length;
  83566. var c = BABYLON.Vector3.Distance(bonePos, target);
  83567. if (this._maxReach > 0) {
  83568. c = Math.min(this._maxReach, c);
  83569. }
  83570. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  83571. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  83572. if (acosa > 1) {
  83573. acosa = 1;
  83574. }
  83575. if (acosb > 1) {
  83576. acosb = 1;
  83577. }
  83578. if (acosa < -1) {
  83579. acosa = -1;
  83580. }
  83581. if (acosb < -1) {
  83582. acosb = -1;
  83583. }
  83584. var angA = Math.acos(acosa);
  83585. var angB = Math.acos(acosb);
  83586. var angC = -angA - angB;
  83587. if (this._rightHandedSystem) {
  83588. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  83589. mat2.multiplyToRef(mat1, mat1);
  83590. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  83591. mat2.multiplyToRef(mat1, mat1);
  83592. }
  83593. else {
  83594. var _tmpVec = BoneIKController._tmpVecs[5];
  83595. _tmpVec.copyFrom(this._bendAxis);
  83596. _tmpVec.x *= -1;
  83597. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  83598. mat2.multiplyToRef(mat1, mat1);
  83599. }
  83600. if (this.poleAngle) {
  83601. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  83602. mat1.multiplyToRef(mat2, mat1);
  83603. }
  83604. if (this._bone1) {
  83605. if (this.slerpAmount < 1) {
  83606. if (!this._slerping) {
  83607. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  83608. }
  83609. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  83610. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  83611. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  83612. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  83613. this._slerping = true;
  83614. }
  83615. else {
  83616. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  83617. this._bone1Mat.copyFrom(mat1);
  83618. this._slerping = false;
  83619. }
  83620. }
  83621. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  83622. this._bone2Ang = angC;
  83623. };
  83624. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83625. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  83626. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83627. return BoneIKController;
  83628. }());
  83629. BABYLON.BoneIKController = BoneIKController;
  83630. })(BABYLON || (BABYLON = {}));
  83631. //# sourceMappingURL=babylon.boneIKController.js.map
  83632. var BABYLON;
  83633. (function (BABYLON) {
  83634. /**
  83635. * Class used to make a bone look toward a point in space
  83636. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  83637. */
  83638. var BoneLookController = /** @class */ (function () {
  83639. /**
  83640. * Create a BoneLookController
  83641. * @param mesh the mesh that the bone belongs to
  83642. * @param bone the bone that will be looking to the target
  83643. * @param target the target Vector3 to look at
  83644. * @param settings optional settings:
  83645. * * maxYaw: the maximum angle the bone will yaw to
  83646. * * minYaw: the minimum angle the bone will yaw to
  83647. * * maxPitch: the maximum angle the bone will pitch to
  83648. * * minPitch: the minimum angle the bone will yaw to
  83649. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  83650. * * upAxis: the up axis of the coordinate system
  83651. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  83652. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  83653. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  83654. * * adjustYaw: used to make an adjustment to the yaw of the bone
  83655. * * adjustPitch: used to make an adjustment to the pitch of the bone
  83656. * * adjustRoll: used to make an adjustment to the roll of the bone
  83657. **/
  83658. function BoneLookController(mesh, bone, target, options) {
  83659. /**
  83660. * The up axis of the coordinate system that is used when the bone is rotated
  83661. */
  83662. this.upAxis = BABYLON.Vector3.Up();
  83663. /**
  83664. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  83665. */
  83666. this.upAxisSpace = BABYLON.Space.LOCAL;
  83667. /**
  83668. * Used to make an adjustment to the yaw of the bone
  83669. */
  83670. this.adjustYaw = 0;
  83671. /**
  83672. * Used to make an adjustment to the pitch of the bone
  83673. */
  83674. this.adjustPitch = 0;
  83675. /**
  83676. * Used to make an adjustment to the roll of the bone
  83677. */
  83678. this.adjustRoll = 0;
  83679. /**
  83680. * 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)
  83681. */
  83682. this.slerpAmount = 1;
  83683. this._boneQuat = BABYLON.Quaternion.Identity();
  83684. this._slerping = false;
  83685. this._firstFrameSkipped = false;
  83686. this._fowardAxis = BABYLON.Vector3.Forward();
  83687. this.mesh = mesh;
  83688. this.bone = bone;
  83689. this.target = target;
  83690. if (options) {
  83691. if (options.adjustYaw) {
  83692. this.adjustYaw = options.adjustYaw;
  83693. }
  83694. if (options.adjustPitch) {
  83695. this.adjustPitch = options.adjustPitch;
  83696. }
  83697. if (options.adjustRoll) {
  83698. this.adjustRoll = options.adjustRoll;
  83699. }
  83700. if (options.maxYaw != null) {
  83701. this.maxYaw = options.maxYaw;
  83702. }
  83703. else {
  83704. this.maxYaw = Math.PI;
  83705. }
  83706. if (options.minYaw != null) {
  83707. this.minYaw = options.minYaw;
  83708. }
  83709. else {
  83710. this.minYaw = -Math.PI;
  83711. }
  83712. if (options.maxPitch != null) {
  83713. this.maxPitch = options.maxPitch;
  83714. }
  83715. else {
  83716. this.maxPitch = Math.PI;
  83717. }
  83718. if (options.minPitch != null) {
  83719. this.minPitch = options.minPitch;
  83720. }
  83721. else {
  83722. this.minPitch = -Math.PI;
  83723. }
  83724. if (options.slerpAmount != null) {
  83725. this.slerpAmount = options.slerpAmount;
  83726. }
  83727. if (options.upAxis != null) {
  83728. this.upAxis = options.upAxis;
  83729. }
  83730. if (options.upAxisSpace != null) {
  83731. this.upAxisSpace = options.upAxisSpace;
  83732. }
  83733. if (options.yawAxis != null || options.pitchAxis != null) {
  83734. var newYawAxis = BABYLON.Axis.Y;
  83735. var newPitchAxis = BABYLON.Axis.X;
  83736. if (options.yawAxis != null) {
  83737. newYawAxis = options.yawAxis.clone();
  83738. newYawAxis.normalize();
  83739. }
  83740. if (options.pitchAxis != null) {
  83741. newPitchAxis = options.pitchAxis.clone();
  83742. newPitchAxis.normalize();
  83743. }
  83744. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  83745. this._transformYawPitch = BABYLON.Matrix.Identity();
  83746. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  83747. this._transformYawPitchInv = this._transformYawPitch.clone();
  83748. this._transformYawPitch.invert();
  83749. }
  83750. }
  83751. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  83752. this.upAxisSpace = BABYLON.Space.LOCAL;
  83753. }
  83754. }
  83755. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  83756. /**
  83757. * Gets or sets the minimum yaw angle that the bone can look to
  83758. */
  83759. get: function () {
  83760. return this._minYaw;
  83761. },
  83762. set: function (value) {
  83763. this._minYaw = value;
  83764. this._minYawSin = Math.sin(value);
  83765. this._minYawCos = Math.cos(value);
  83766. if (this._maxYaw != null) {
  83767. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83768. this._yawRange = this._maxYaw - this._minYaw;
  83769. }
  83770. },
  83771. enumerable: true,
  83772. configurable: true
  83773. });
  83774. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  83775. /**
  83776. * Gets or sets the maximum yaw angle that the bone can look to
  83777. */
  83778. get: function () {
  83779. return this._maxYaw;
  83780. },
  83781. set: function (value) {
  83782. this._maxYaw = value;
  83783. this._maxYawSin = Math.sin(value);
  83784. this._maxYawCos = Math.cos(value);
  83785. if (this._minYaw != null) {
  83786. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83787. this._yawRange = this._maxYaw - this._minYaw;
  83788. }
  83789. },
  83790. enumerable: true,
  83791. configurable: true
  83792. });
  83793. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  83794. /**
  83795. * Gets or sets the minimum pitch angle that the bone can look to
  83796. */
  83797. get: function () {
  83798. return this._minPitch;
  83799. },
  83800. set: function (value) {
  83801. this._minPitch = value;
  83802. this._minPitchTan = Math.tan(value);
  83803. },
  83804. enumerable: true,
  83805. configurable: true
  83806. });
  83807. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  83808. /**
  83809. * Gets or sets the maximum pitch angle that the bone can look to
  83810. */
  83811. get: function () {
  83812. return this._maxPitch;
  83813. },
  83814. set: function (value) {
  83815. this._maxPitch = value;
  83816. this._maxPitchTan = Math.tan(value);
  83817. },
  83818. enumerable: true,
  83819. configurable: true
  83820. });
  83821. /**
  83822. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  83823. */
  83824. BoneLookController.prototype.update = function () {
  83825. //skip the first frame when slerping so that the mesh rotation is correct
  83826. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  83827. this._firstFrameSkipped = true;
  83828. return;
  83829. }
  83830. var bone = this.bone;
  83831. var bonePos = BoneLookController._tmpVecs[0];
  83832. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  83833. var target = this.target;
  83834. var _tmpMat1 = BoneLookController._tmpMats[0];
  83835. var _tmpMat2 = BoneLookController._tmpMats[1];
  83836. var mesh = this.mesh;
  83837. var parentBone = bone.getParent();
  83838. var upAxis = BoneLookController._tmpVecs[1];
  83839. upAxis.copyFrom(this.upAxis);
  83840. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  83841. if (this._transformYawPitch) {
  83842. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  83843. }
  83844. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  83845. }
  83846. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  83847. mesh.getDirectionToRef(upAxis, upAxis);
  83848. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  83849. upAxis.normalize();
  83850. }
  83851. }
  83852. var checkYaw = false;
  83853. var checkPitch = false;
  83854. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  83855. checkYaw = true;
  83856. }
  83857. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  83858. checkPitch = true;
  83859. }
  83860. if (checkYaw || checkPitch) {
  83861. var spaceMat = BoneLookController._tmpMats[2];
  83862. var spaceMatInv = BoneLookController._tmpMats[3];
  83863. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  83864. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  83865. }
  83866. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  83867. spaceMat.copyFrom(mesh.getWorldMatrix());
  83868. }
  83869. else {
  83870. var forwardAxis = BoneLookController._tmpVecs[2];
  83871. forwardAxis.copyFrom(this._fowardAxis);
  83872. if (this._transformYawPitch) {
  83873. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  83874. }
  83875. if (parentBone) {
  83876. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  83877. }
  83878. else {
  83879. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  83880. }
  83881. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  83882. rightAxis.normalize();
  83883. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  83884. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  83885. }
  83886. spaceMat.invertToRef(spaceMatInv);
  83887. var xzlen = null;
  83888. if (checkPitch) {
  83889. var localTarget = BoneLookController._tmpVecs[3];
  83890. target.subtractToRef(bonePos, localTarget);
  83891. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83892. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83893. var pitch = Math.atan2(localTarget.y, xzlen);
  83894. var newPitch = pitch;
  83895. if (pitch > this._maxPitch) {
  83896. localTarget.y = this._maxPitchTan * xzlen;
  83897. newPitch = this._maxPitch;
  83898. }
  83899. else if (pitch < this._minPitch) {
  83900. localTarget.y = this._minPitchTan * xzlen;
  83901. newPitch = this._minPitch;
  83902. }
  83903. if (pitch != newPitch) {
  83904. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83905. localTarget.addInPlace(bonePos);
  83906. target = localTarget;
  83907. }
  83908. }
  83909. if (checkYaw) {
  83910. var localTarget = BoneLookController._tmpVecs[4];
  83911. target.subtractToRef(bonePos, localTarget);
  83912. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83913. var yaw = Math.atan2(localTarget.x, localTarget.z);
  83914. var newYaw = yaw;
  83915. if (yaw > this._maxYaw || yaw < this._minYaw) {
  83916. if (xzlen == null) {
  83917. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83918. }
  83919. if (this._yawRange > Math.PI) {
  83920. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  83921. localTarget.z = this._maxYawCos * xzlen;
  83922. localTarget.x = this._maxYawSin * xzlen;
  83923. newYaw = this._maxYaw;
  83924. }
  83925. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  83926. localTarget.z = this._minYawCos * xzlen;
  83927. localTarget.x = this._minYawSin * xzlen;
  83928. newYaw = this._minYaw;
  83929. }
  83930. }
  83931. else {
  83932. if (yaw > this._maxYaw) {
  83933. localTarget.z = this._maxYawCos * xzlen;
  83934. localTarget.x = this._maxYawSin * xzlen;
  83935. newYaw = this._maxYaw;
  83936. }
  83937. else if (yaw < this._minYaw) {
  83938. localTarget.z = this._minYawCos * xzlen;
  83939. localTarget.x = this._minYawSin * xzlen;
  83940. newYaw = this._minYaw;
  83941. }
  83942. }
  83943. }
  83944. if (this._slerping && this._yawRange > Math.PI) {
  83945. //are we going to be crossing into the min/max region?
  83946. var boneFwd = BoneLookController._tmpVecs[8];
  83947. boneFwd.copyFrom(BABYLON.Axis.Z);
  83948. if (this._transformYawPitch) {
  83949. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  83950. }
  83951. var boneRotMat = BoneLookController._tmpMats[4];
  83952. this._boneQuat.toRotationMatrix(boneRotMat);
  83953. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  83954. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  83955. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  83956. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  83957. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  83958. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  83959. if (angBtwTar > angBtwMidYaw) {
  83960. if (xzlen == null) {
  83961. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83962. }
  83963. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  83964. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  83965. if (angBtwMin < angBtwMax) {
  83966. newYaw = boneYaw + Math.PI * .75;
  83967. localTarget.z = Math.cos(newYaw) * xzlen;
  83968. localTarget.x = Math.sin(newYaw) * xzlen;
  83969. }
  83970. else {
  83971. newYaw = boneYaw - Math.PI * .75;
  83972. localTarget.z = Math.cos(newYaw) * xzlen;
  83973. localTarget.x = Math.sin(newYaw) * xzlen;
  83974. }
  83975. }
  83976. }
  83977. if (yaw != newYaw) {
  83978. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83979. localTarget.addInPlace(bonePos);
  83980. target = localTarget;
  83981. }
  83982. }
  83983. }
  83984. var zaxis = BoneLookController._tmpVecs[5];
  83985. var xaxis = BoneLookController._tmpVecs[6];
  83986. var yaxis = BoneLookController._tmpVecs[7];
  83987. var _tmpQuat = BoneLookController._tmpQuat;
  83988. target.subtractToRef(bonePos, zaxis);
  83989. zaxis.normalize();
  83990. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  83991. xaxis.normalize();
  83992. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  83993. yaxis.normalize();
  83994. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  83995. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  83996. return;
  83997. }
  83998. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  83999. return;
  84000. }
  84001. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84002. return;
  84003. }
  84004. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84005. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84006. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84007. }
  84008. if (this.slerpAmount < 1) {
  84009. if (!this._slerping) {
  84010. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84011. }
  84012. if (this._transformYawPitch) {
  84013. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84014. }
  84015. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84016. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84017. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84018. this._slerping = true;
  84019. }
  84020. else {
  84021. if (this._transformYawPitch) {
  84022. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84023. }
  84024. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84025. this._slerping = false;
  84026. }
  84027. };
  84028. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84029. var angDiff = ang2 - ang1;
  84030. angDiff %= Math.PI * 2;
  84031. if (angDiff > Math.PI) {
  84032. angDiff -= Math.PI * 2;
  84033. }
  84034. else if (angDiff < -Math.PI) {
  84035. angDiff += Math.PI * 2;
  84036. }
  84037. return angDiff;
  84038. };
  84039. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84040. ang1 %= (2 * Math.PI);
  84041. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84042. ang2 %= (2 * Math.PI);
  84043. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84044. var ab = 0;
  84045. if (ang1 < ang2) {
  84046. ab = ang2 - ang1;
  84047. }
  84048. else {
  84049. ab = ang1 - ang2;
  84050. }
  84051. if (ab > Math.PI) {
  84052. ab = Math.PI * 2 - ab;
  84053. }
  84054. return ab;
  84055. };
  84056. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84057. ang %= (2 * Math.PI);
  84058. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84059. ang1 %= (2 * Math.PI);
  84060. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84061. ang2 %= (2 * Math.PI);
  84062. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84063. if (ang1 < ang2) {
  84064. if (ang > ang1 && ang < ang2) {
  84065. return true;
  84066. }
  84067. }
  84068. else {
  84069. if (ang > ang2 && ang < ang1) {
  84070. return true;
  84071. }
  84072. }
  84073. return false;
  84074. };
  84075. 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()];
  84076. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84077. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84078. return BoneLookController;
  84079. }());
  84080. BABYLON.BoneLookController = BoneLookController;
  84081. })(BABYLON || (BABYLON = {}));
  84082. //# sourceMappingURL=babylon.boneLookController.js.map
  84083. var BABYLON;
  84084. (function (BABYLON) {
  84085. /**
  84086. * Class used to handle skinning animations
  84087. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84088. */
  84089. var Skeleton = /** @class */ (function () {
  84090. /**
  84091. * Creates a new skeleton
  84092. * @param name defines the skeleton name
  84093. * @param id defines the skeleton Id
  84094. * @param scene defines the hosting scene
  84095. */
  84096. function Skeleton(
  84097. /** defines the skeleton name */
  84098. name,
  84099. /** defines the skeleton Id */
  84100. id, scene) {
  84101. this.name = name;
  84102. this.id = id;
  84103. /**
  84104. * Gets the list of child bones
  84105. */
  84106. this.bones = new Array();
  84107. /**
  84108. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  84109. */
  84110. this.needInitialSkinMatrix = false;
  84111. this._isDirty = true;
  84112. this._meshesWithPoseMatrix = new Array();
  84113. this._identity = BABYLON.Matrix.Identity();
  84114. this._ranges = {};
  84115. this._lastAbsoluteTransformsUpdateId = -1;
  84116. /**
  84117. * Specifies if the skeleton should be serialized
  84118. */
  84119. this.doNotSerialize = false;
  84120. this._animationPropertiesOverride = null;
  84121. // Events
  84122. /**
  84123. * An observable triggered before computing the skeleton's matrices
  84124. */
  84125. this.onBeforeComputeObservable = new BABYLON.Observable();
  84126. this.bones = [];
  84127. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84128. scene.skeletons.push(this);
  84129. //make sure it will recalculate the matrix next time prepare is called.
  84130. this._isDirty = true;
  84131. }
  84132. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  84133. /**
  84134. * Gets or sets the animation properties override
  84135. */
  84136. get: function () {
  84137. if (!this._animationPropertiesOverride) {
  84138. return this._scene.animationPropertiesOverride;
  84139. }
  84140. return this._animationPropertiesOverride;
  84141. },
  84142. set: function (value) {
  84143. this._animationPropertiesOverride = value;
  84144. },
  84145. enumerable: true,
  84146. configurable: true
  84147. });
  84148. // Members
  84149. /**
  84150. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  84151. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  84152. * @returns a Float32Array containing matrices data
  84153. */
  84154. Skeleton.prototype.getTransformMatrices = function (mesh) {
  84155. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  84156. return mesh._bonesTransformMatrices;
  84157. }
  84158. if (!this._transformMatrices) {
  84159. this.prepare();
  84160. }
  84161. return this._transformMatrices;
  84162. };
  84163. /**
  84164. * Gets the current hosting scene
  84165. * @returns a scene object
  84166. */
  84167. Skeleton.prototype.getScene = function () {
  84168. return this._scene;
  84169. };
  84170. // Methods
  84171. /**
  84172. * Gets a string representing the current skeleton data
  84173. * @param fullDetails defines a boolean indicating if we want a verbose version
  84174. * @returns a string representing the current skeleton data
  84175. */
  84176. Skeleton.prototype.toString = function (fullDetails) {
  84177. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  84178. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  84179. if (fullDetails) {
  84180. ret += ", Ranges: {";
  84181. var first = true;
  84182. for (var name_1 in this._ranges) {
  84183. if (first) {
  84184. ret += ", ";
  84185. first = false;
  84186. }
  84187. ret += name_1;
  84188. }
  84189. ret += "}";
  84190. }
  84191. return ret;
  84192. };
  84193. /**
  84194. * Get bone's index searching by name
  84195. * @param name defines bone's name to search for
  84196. * @return the indice of the bone. Returns -1 if not found
  84197. */
  84198. Skeleton.prototype.getBoneIndexByName = function (name) {
  84199. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  84200. if (this.bones[boneIndex].name === name) {
  84201. return boneIndex;
  84202. }
  84203. }
  84204. return -1;
  84205. };
  84206. /**
  84207. * Creater a new animation range
  84208. * @param name defines the name of the range
  84209. * @param from defines the start key
  84210. * @param to defines the end key
  84211. */
  84212. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  84213. // check name not already in use
  84214. if (!this._ranges[name]) {
  84215. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  84216. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84217. if (this.bones[i].animations[0]) {
  84218. this.bones[i].animations[0].createRange(name, from, to);
  84219. }
  84220. }
  84221. }
  84222. };
  84223. /**
  84224. * Delete a specific animation range
  84225. * @param name defines the name of the range
  84226. * @param deleteFrames defines if frames must be removed as well
  84227. */
  84228. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  84229. if (deleteFrames === void 0) { deleteFrames = true; }
  84230. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84231. if (this.bones[i].animations[0]) {
  84232. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  84233. }
  84234. }
  84235. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  84236. };
  84237. /**
  84238. * Gets a specific animation range
  84239. * @param name defines the name of the range to look for
  84240. * @returns the requested animation range or null if not found
  84241. */
  84242. Skeleton.prototype.getAnimationRange = function (name) {
  84243. return this._ranges[name];
  84244. };
  84245. /**
  84246. * Gets the list of all animation ranges defined on this skeleton
  84247. * @returns an array
  84248. */
  84249. Skeleton.prototype.getAnimationRanges = function () {
  84250. var animationRanges = [];
  84251. var name;
  84252. var i = 0;
  84253. for (name in this._ranges) {
  84254. animationRanges[i] = this._ranges[name];
  84255. i++;
  84256. }
  84257. return animationRanges;
  84258. };
  84259. /**
  84260. * Copy animation range from a source skeleton.
  84261. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84262. * @param source defines the source skeleton
  84263. * @param name defines the name of the range to copy
  84264. * @param rescaleAsRequired defines if rescaling must be applied if required
  84265. * @returns true if operation was successful
  84266. */
  84267. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84268. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84269. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84270. return false;
  84271. }
  84272. var ret = true;
  84273. var frameOffset = this._getHighestAnimationFrame() + 1;
  84274. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84275. var boneDict = {};
  84276. var sourceBones = source.bones;
  84277. var nBones;
  84278. var i;
  84279. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84280. boneDict[sourceBones[i].name] = sourceBones[i];
  84281. }
  84282. if (this.bones.length !== sourceBones.length) {
  84283. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84284. ret = false;
  84285. }
  84286. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84287. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84288. var boneName = this.bones[i].name;
  84289. var sourceBone = boneDict[boneName];
  84290. if (sourceBone) {
  84291. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84292. }
  84293. else {
  84294. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84295. ret = false;
  84296. }
  84297. }
  84298. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84299. var range = source.getAnimationRange(name);
  84300. if (range) {
  84301. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84302. }
  84303. return ret;
  84304. };
  84305. /**
  84306. * Forces the skeleton to go to rest pose
  84307. */
  84308. Skeleton.prototype.returnToRest = function () {
  84309. for (var index = 0; index < this.bones.length; index++) {
  84310. this.bones[index].returnToRest();
  84311. }
  84312. };
  84313. Skeleton.prototype._getHighestAnimationFrame = function () {
  84314. var ret = 0;
  84315. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84316. if (this.bones[i].animations[0]) {
  84317. var highest = this.bones[i].animations[0].getHighestFrame();
  84318. if (ret < highest) {
  84319. ret = highest;
  84320. }
  84321. }
  84322. }
  84323. return ret;
  84324. };
  84325. /**
  84326. * Begin a specific animation range
  84327. * @param name defines the name of the range to start
  84328. * @param loop defines if looping must be turned on (false by default)
  84329. * @param speedRatio defines the speed ratio to apply (1 by default)
  84330. * @param onAnimationEnd defines a callback which will be called when animation will end
  84331. * @returns a new animatable
  84332. */
  84333. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84334. var range = this.getAnimationRange(name);
  84335. if (!range) {
  84336. return null;
  84337. }
  84338. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84339. };
  84340. /** @hidden */
  84341. Skeleton.prototype._markAsDirty = function () {
  84342. this._isDirty = true;
  84343. };
  84344. /** @hidden */
  84345. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84346. this._meshesWithPoseMatrix.push(mesh);
  84347. };
  84348. /** @hidden */
  84349. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84350. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84351. if (index > -1) {
  84352. this._meshesWithPoseMatrix.splice(index, 1);
  84353. }
  84354. };
  84355. /** @hidden */
  84356. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84357. this.onBeforeComputeObservable.notifyObservers(this);
  84358. for (var index = 0; index < this.bones.length; index++) {
  84359. var bone = this.bones[index];
  84360. var parentBone = bone.getParent();
  84361. if (parentBone) {
  84362. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84363. }
  84364. else {
  84365. if (initialSkinMatrix) {
  84366. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84367. }
  84368. else {
  84369. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84370. }
  84371. }
  84372. if (bone._index !== -1) {
  84373. var mappedIndex = bone._index === null ? index : bone._index;
  84374. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84375. }
  84376. }
  84377. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84378. };
  84379. /**
  84380. * Build all resources required to render a skeleton
  84381. */
  84382. Skeleton.prototype.prepare = function () {
  84383. if (!this._isDirty) {
  84384. return;
  84385. }
  84386. if (this.needInitialSkinMatrix) {
  84387. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84388. var mesh = this._meshesWithPoseMatrix[index];
  84389. var poseMatrix = mesh.getPoseMatrix();
  84390. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84391. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84392. }
  84393. if (this._synchronizedWithMesh !== mesh) {
  84394. this._synchronizedWithMesh = mesh;
  84395. // Prepare bones
  84396. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84397. var bone = this.bones[boneIndex];
  84398. if (!bone.getParent()) {
  84399. var matrix = bone.getBaseMatrix();
  84400. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84401. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84402. }
  84403. }
  84404. }
  84405. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84406. }
  84407. }
  84408. else {
  84409. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84410. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84411. }
  84412. this._computeTransformMatrices(this._transformMatrices, null);
  84413. }
  84414. this._isDirty = false;
  84415. this._scene._activeBones.addCount(this.bones.length, false);
  84416. };
  84417. /**
  84418. * Gets the list of animatables currently running for this skeleton
  84419. * @returns an array of animatables
  84420. */
  84421. Skeleton.prototype.getAnimatables = function () {
  84422. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84423. this._animatables = [];
  84424. for (var index = 0; index < this.bones.length; index++) {
  84425. this._animatables.push(this.bones[index]);
  84426. }
  84427. }
  84428. return this._animatables;
  84429. };
  84430. /**
  84431. * Clone the current skeleton
  84432. * @param name defines the name of the new skeleton
  84433. * @param id defines the id of the enw skeleton
  84434. * @returns the new skeleton
  84435. */
  84436. Skeleton.prototype.clone = function (name, id) {
  84437. var result = new Skeleton(name, id || name, this._scene);
  84438. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84439. for (var index = 0; index < this.bones.length; index++) {
  84440. var source = this.bones[index];
  84441. var parentBone = null;
  84442. var parent_1 = source.getParent();
  84443. if (parent_1) {
  84444. var parentIndex = this.bones.indexOf(parent_1);
  84445. parentBone = result.bones[parentIndex];
  84446. }
  84447. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84448. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84449. }
  84450. if (this._ranges) {
  84451. result._ranges = {};
  84452. for (var rangeName in this._ranges) {
  84453. var range = this._ranges[rangeName];
  84454. if (range) {
  84455. result._ranges[rangeName] = range.clone();
  84456. }
  84457. }
  84458. }
  84459. this._isDirty = true;
  84460. return result;
  84461. };
  84462. /**
  84463. * Enable animation blending for this skeleton
  84464. * @param blendingSpeed defines the blending speed to apply
  84465. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84466. */
  84467. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84468. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84469. this.bones.forEach(function (bone) {
  84470. bone.animations.forEach(function (animation) {
  84471. animation.enableBlending = true;
  84472. animation.blendingSpeed = blendingSpeed;
  84473. });
  84474. });
  84475. };
  84476. /**
  84477. * Releases all resources associated with the current skeleton
  84478. */
  84479. Skeleton.prototype.dispose = function () {
  84480. this._meshesWithPoseMatrix = [];
  84481. // Animations
  84482. this.getScene().stopAnimation(this);
  84483. // Remove from scene
  84484. this.getScene().removeSkeleton(this);
  84485. };
  84486. /**
  84487. * Serialize the skeleton in a JSON object
  84488. * @returns a JSON object
  84489. */
  84490. Skeleton.prototype.serialize = function () {
  84491. var serializationObject = {};
  84492. serializationObject.name = this.name;
  84493. serializationObject.id = this.id;
  84494. if (this.dimensionsAtRest) {
  84495. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84496. }
  84497. serializationObject.bones = [];
  84498. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84499. for (var index = 0; index < this.bones.length; index++) {
  84500. var bone = this.bones[index];
  84501. var parent_2 = bone.getParent();
  84502. var serializedBone = {
  84503. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84504. name: bone.name,
  84505. matrix: bone.getBaseMatrix().toArray(),
  84506. rest: bone.getRestPose().toArray()
  84507. };
  84508. serializationObject.bones.push(serializedBone);
  84509. if (bone.length) {
  84510. serializedBone.length = bone.length;
  84511. }
  84512. if (bone.metadata) {
  84513. serializedBone.metadata = bone.metadata;
  84514. }
  84515. if (bone.animations && bone.animations.length > 0) {
  84516. serializedBone.animation = bone.animations[0].serialize();
  84517. }
  84518. serializationObject.ranges = [];
  84519. for (var name in this._ranges) {
  84520. var source = this._ranges[name];
  84521. if (!source) {
  84522. continue;
  84523. }
  84524. var range = {};
  84525. range.name = name;
  84526. range.from = source.from;
  84527. range.to = source.to;
  84528. serializationObject.ranges.push(range);
  84529. }
  84530. }
  84531. return serializationObject;
  84532. };
  84533. /**
  84534. * Creates a new skeleton from serialized data
  84535. * @param parsedSkeleton defines the serialized data
  84536. * @param scene defines the hosting scene
  84537. * @returns a new skeleton
  84538. */
  84539. Skeleton.Parse = function (parsedSkeleton, scene) {
  84540. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  84541. if (parsedSkeleton.dimensionsAtRest) {
  84542. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  84543. }
  84544. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  84545. var index;
  84546. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  84547. var parsedBone = parsedSkeleton.bones[index];
  84548. var parentBone = null;
  84549. if (parsedBone.parentBoneIndex > -1) {
  84550. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  84551. }
  84552. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  84553. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  84554. if (parsedBone.length) {
  84555. bone.length = parsedBone.length;
  84556. }
  84557. if (parsedBone.metadata) {
  84558. bone.metadata = parsedBone.metadata;
  84559. }
  84560. if (parsedBone.animation) {
  84561. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  84562. }
  84563. }
  84564. // placed after bones, so createAnimationRange can cascade down
  84565. if (parsedSkeleton.ranges) {
  84566. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  84567. var data = parsedSkeleton.ranges[index];
  84568. skeleton.createAnimationRange(data.name, data.from, data.to);
  84569. }
  84570. }
  84571. return skeleton;
  84572. };
  84573. /**
  84574. * Compute all node absolute transforms
  84575. * @param forceUpdate defines if computation must be done even if cache is up to date
  84576. */
  84577. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  84578. if (forceUpdate === void 0) { forceUpdate = false; }
  84579. var renderId = this._scene.getRenderId();
  84580. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  84581. this.bones[0].computeAbsoluteTransforms();
  84582. this._lastAbsoluteTransformsUpdateId = renderId;
  84583. }
  84584. };
  84585. /**
  84586. * Gets the root pose matrix
  84587. * @returns a matrix
  84588. */
  84589. Skeleton.prototype.getPoseMatrix = function () {
  84590. var poseMatrix = null;
  84591. if (this._meshesWithPoseMatrix.length > 0) {
  84592. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  84593. }
  84594. return poseMatrix;
  84595. };
  84596. /**
  84597. * Sorts bones per internal index
  84598. */
  84599. Skeleton.prototype.sortBones = function () {
  84600. var bones = new Array();
  84601. var visited = new Array(this.bones.length);
  84602. for (var index = 0; index < this.bones.length; index++) {
  84603. this._sortBones(index, bones, visited);
  84604. }
  84605. this.bones = bones;
  84606. };
  84607. Skeleton.prototype._sortBones = function (index, bones, visited) {
  84608. if (visited[index]) {
  84609. return;
  84610. }
  84611. visited[index] = true;
  84612. var bone = this.bones[index];
  84613. if (bone._index === undefined) {
  84614. bone._index = index;
  84615. }
  84616. var parentBone = bone.getParent();
  84617. if (parentBone) {
  84618. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  84619. }
  84620. bones.push(bone);
  84621. };
  84622. return Skeleton;
  84623. }());
  84624. BABYLON.Skeleton = Skeleton;
  84625. })(BABYLON || (BABYLON = {}));
  84626. //# sourceMappingURL=babylon.skeleton.js.map
  84627. var BABYLON;
  84628. (function (BABYLON) {
  84629. ;
  84630. /**
  84631. * This groups tools to convert HDR texture to native colors array.
  84632. */
  84633. var HDRTools = /** @class */ (function () {
  84634. function HDRTools() {
  84635. }
  84636. HDRTools.Ldexp = function (mantissa, exponent) {
  84637. if (exponent > 1023) {
  84638. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  84639. }
  84640. if (exponent < -1074) {
  84641. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  84642. }
  84643. return mantissa * Math.pow(2, exponent);
  84644. };
  84645. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  84646. if (exponent > 0) { /*nonzero pixel*/
  84647. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  84648. float32array[index + 0] = red * exponent;
  84649. float32array[index + 1] = green * exponent;
  84650. float32array[index + 2] = blue * exponent;
  84651. }
  84652. else {
  84653. float32array[index + 0] = 0;
  84654. float32array[index + 1] = 0;
  84655. float32array[index + 2] = 0;
  84656. }
  84657. };
  84658. HDRTools.readStringLine = function (uint8array, startIndex) {
  84659. var line = "";
  84660. var character = "";
  84661. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  84662. character = String.fromCharCode(uint8array[i]);
  84663. if (character == "\n") {
  84664. break;
  84665. }
  84666. line += character;
  84667. }
  84668. return line;
  84669. };
  84670. /**
  84671. * Reads header information from an RGBE texture stored in a native array.
  84672. * More information on this format are available here:
  84673. * https://en.wikipedia.org/wiki/RGBE_image_format
  84674. *
  84675. * @param uint8array The binary file stored in native array.
  84676. * @return The header information.
  84677. */
  84678. HDRTools.RGBE_ReadHeader = function (uint8array) {
  84679. var height = 0;
  84680. var width = 0;
  84681. var line = this.readStringLine(uint8array, 0);
  84682. if (line[0] != '#' || line[1] != '?') {
  84683. throw "Bad HDR Format.";
  84684. }
  84685. var endOfHeader = false;
  84686. var findFormat = false;
  84687. var lineIndex = 0;
  84688. do {
  84689. lineIndex += (line.length + 1);
  84690. line = this.readStringLine(uint8array, lineIndex);
  84691. if (line == "FORMAT=32-bit_rle_rgbe") {
  84692. findFormat = true;
  84693. }
  84694. else if (line.length == 0) {
  84695. endOfHeader = true;
  84696. }
  84697. } while (!endOfHeader);
  84698. if (!findFormat) {
  84699. throw "HDR Bad header format, unsupported FORMAT";
  84700. }
  84701. lineIndex += (line.length + 1);
  84702. line = this.readStringLine(uint8array, lineIndex);
  84703. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  84704. var match = sizeRegexp.exec(line);
  84705. // TODO. Support +Y and -X if needed.
  84706. if (!match || match.length < 3) {
  84707. throw "HDR Bad header format, no size";
  84708. }
  84709. width = parseInt(match[2]);
  84710. height = parseInt(match[1]);
  84711. if (width < 8 || width > 0x7fff) {
  84712. throw "HDR Bad header format, unsupported size";
  84713. }
  84714. lineIndex += (line.length + 1);
  84715. return {
  84716. height: height,
  84717. width: width,
  84718. dataPosition: lineIndex
  84719. };
  84720. };
  84721. /**
  84722. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  84723. * This RGBE texture needs to store the information as a panorama.
  84724. *
  84725. * More information on this format are available here:
  84726. * https://en.wikipedia.org/wiki/RGBE_image_format
  84727. *
  84728. * @param buffer The binary file stored in an array buffer.
  84729. * @param size The expected size of the extracted cubemap.
  84730. * @return The Cube Map information.
  84731. */
  84732. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  84733. var uint8array = new Uint8Array(buffer);
  84734. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  84735. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84736. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  84737. return cubeMapData;
  84738. };
  84739. /**
  84740. * Returns the pixels data extracted from an RGBE texture.
  84741. * This pixels will be stored left to right up to down in the R G B order in one array.
  84742. *
  84743. * More information on this format are available here:
  84744. * https://en.wikipedia.org/wiki/RGBE_image_format
  84745. *
  84746. * @param uint8array The binary file stored in an array buffer.
  84747. * @param hdrInfo The header information of the file.
  84748. * @return The pixels data in RGB right to left up to down order.
  84749. */
  84750. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  84751. // Keep for multi format supports.
  84752. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84753. };
  84754. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  84755. var num_scanlines = hdrInfo.height;
  84756. var scanline_width = hdrInfo.width;
  84757. var a, b, c, d, count;
  84758. var dataIndex = hdrInfo.dataPosition;
  84759. var index = 0, endIndex = 0, i = 0;
  84760. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  84761. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  84762. // 3 channels of 4 bytes per pixel in float.
  84763. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  84764. var resultArray = new Float32Array(resultBuffer);
  84765. // read in each successive scanline
  84766. while (num_scanlines > 0) {
  84767. a = uint8array[dataIndex++];
  84768. b = uint8array[dataIndex++];
  84769. c = uint8array[dataIndex++];
  84770. d = uint8array[dataIndex++];
  84771. if (a != 2 || b != 2 || (c & 0x80)) {
  84772. // this file is not run length encoded
  84773. throw "HDR Bad header format, not RLE";
  84774. }
  84775. if (((c << 8) | d) != scanline_width) {
  84776. throw "HDR Bad header format, wrong scan line width";
  84777. }
  84778. index = 0;
  84779. // read each of the four channels for the scanline into the buffer
  84780. for (i = 0; i < 4; i++) {
  84781. endIndex = (i + 1) * scanline_width;
  84782. while (index < endIndex) {
  84783. a = uint8array[dataIndex++];
  84784. b = uint8array[dataIndex++];
  84785. if (a > 128) {
  84786. // a run of the same value
  84787. count = a - 128;
  84788. if ((count == 0) || (count > endIndex - index)) {
  84789. throw "HDR Bad Format, bad scanline data (run)";
  84790. }
  84791. while (count-- > 0) {
  84792. scanLineArray[index++] = b;
  84793. }
  84794. }
  84795. else {
  84796. // a non-run
  84797. count = a;
  84798. if ((count == 0) || (count > endIndex - index)) {
  84799. throw "HDR Bad Format, bad scanline data (non-run)";
  84800. }
  84801. scanLineArray[index++] = b;
  84802. if (--count > 0) {
  84803. for (var j = 0; j < count; j++) {
  84804. scanLineArray[index++] = uint8array[dataIndex++];
  84805. }
  84806. }
  84807. }
  84808. }
  84809. }
  84810. // now convert data from buffer into floats
  84811. for (i = 0; i < scanline_width; i++) {
  84812. a = scanLineArray[i];
  84813. b = scanLineArray[i + scanline_width];
  84814. c = scanLineArray[i + 2 * scanline_width];
  84815. d = scanLineArray[i + 3 * scanline_width];
  84816. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  84817. }
  84818. num_scanlines--;
  84819. }
  84820. return resultArray;
  84821. };
  84822. return HDRTools;
  84823. }());
  84824. BABYLON.HDRTools = HDRTools;
  84825. })(BABYLON || (BABYLON = {}));
  84826. //# sourceMappingURL=babylon.hdr.js.map
  84827. var BABYLON;
  84828. (function (BABYLON) {
  84829. /**
  84830. * This represents a texture coming from an HDR input.
  84831. *
  84832. * The only supported format is currently panorama picture stored in RGBE format.
  84833. * Example of such files can be found on HDRLib: http://hdrlib.com/
  84834. */
  84835. var HDRCubeTexture = /** @class */ (function (_super) {
  84836. __extends(HDRCubeTexture, _super);
  84837. /**
  84838. * Instantiates an HDRTexture from the following parameters.
  84839. *
  84840. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  84841. * @param scene The scene the texture will be used in
  84842. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  84843. * @param noMipmap Forces to not generate the mipmap if true
  84844. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  84845. * @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)
  84846. * @param reserved Reserved flag for internal use.
  84847. */
  84848. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  84849. if (noMipmap === void 0) { noMipmap = false; }
  84850. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84851. if (gammaSpace === void 0) { gammaSpace = false; }
  84852. if (reserved === void 0) { reserved = false; }
  84853. if (onLoad === void 0) { onLoad = null; }
  84854. if (onError === void 0) { onError = null; }
  84855. var _this = _super.call(this, scene) || this;
  84856. _this._generateHarmonics = true;
  84857. _this._onLoad = null;
  84858. _this._onError = null;
  84859. /**
  84860. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  84861. */
  84862. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  84863. _this._isBlocking = true;
  84864. _this._rotationY = 0;
  84865. /**
  84866. * Gets or sets the center of the bounding box associated with the cube texture
  84867. * It must define where the camera used to render the texture was set
  84868. */
  84869. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  84870. if (!url) {
  84871. return _this;
  84872. }
  84873. _this.name = url;
  84874. _this.url = url;
  84875. _this.hasAlpha = false;
  84876. _this.isCube = true;
  84877. _this._textureMatrix = BABYLON.Matrix.Identity();
  84878. _this._onLoad = onLoad;
  84879. _this._onError = onError;
  84880. _this.gammaSpace = gammaSpace;
  84881. _this._noMipmap = noMipmap;
  84882. _this._size = size;
  84883. _this._texture = _this._getFromCache(url, _this._noMipmap);
  84884. if (!_this._texture) {
  84885. if (!scene.useDelayedTextureLoading) {
  84886. _this.loadTexture();
  84887. }
  84888. else {
  84889. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84890. }
  84891. }
  84892. return _this;
  84893. }
  84894. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  84895. /**
  84896. * Gets wether or not the texture is blocking during loading.
  84897. */
  84898. get: function () {
  84899. return this._isBlocking;
  84900. },
  84901. /**
  84902. * Sets wether or not the texture is blocking during loading.
  84903. */
  84904. set: function (value) {
  84905. this._isBlocking = value;
  84906. },
  84907. enumerable: true,
  84908. configurable: true
  84909. });
  84910. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  84911. /**
  84912. * Gets texture matrix rotation angle around Y axis radians.
  84913. */
  84914. get: function () {
  84915. return this._rotationY;
  84916. },
  84917. /**
  84918. * Sets texture matrix rotation angle around Y axis in radians.
  84919. */
  84920. set: function (value) {
  84921. this._rotationY = value;
  84922. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  84923. },
  84924. enumerable: true,
  84925. configurable: true
  84926. });
  84927. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  84928. get: function () {
  84929. return this._boundingBoxSize;
  84930. },
  84931. /**
  84932. * Gets or sets the size of the bounding box associated with the cube texture
  84933. * When defined, the cubemap will switch to local mode
  84934. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  84935. * @example https://www.babylonjs-playground.com/#RNASML
  84936. */
  84937. set: function (value) {
  84938. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  84939. return;
  84940. }
  84941. this._boundingBoxSize = value;
  84942. var scene = this.getScene();
  84943. if (scene) {
  84944. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  84945. }
  84946. },
  84947. enumerable: true,
  84948. configurable: true
  84949. });
  84950. /**
  84951. * Occurs when the file is raw .hdr file.
  84952. */
  84953. HDRCubeTexture.prototype.loadTexture = function () {
  84954. var _this = this;
  84955. var callback = function (buffer) {
  84956. _this.lodGenerationOffset = 0.0;
  84957. _this.lodGenerationScale = 0.8;
  84958. var scene = _this.getScene();
  84959. if (!scene) {
  84960. return null;
  84961. }
  84962. // Extract the raw linear data.
  84963. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  84964. // Generate harmonics if needed.
  84965. if (_this._generateHarmonics) {
  84966. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  84967. _this.sphericalPolynomial = sphericalPolynomial;
  84968. }
  84969. var results = [];
  84970. var byteArray = null;
  84971. // Push each faces.
  84972. for (var j = 0; j < 6; j++) {
  84973. // Create uintarray fallback.
  84974. if (!scene.getEngine().getCaps().textureFloat) {
  84975. // 3 channels of 1 bytes per pixel in bytes.
  84976. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  84977. byteArray = new Uint8Array(byteBuffer);
  84978. }
  84979. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  84980. // If special cases.
  84981. if (_this.gammaSpace || byteArray) {
  84982. for (var i = 0; i < _this._size * _this._size; i++) {
  84983. // Put in gamma space if requested.
  84984. if (_this.gammaSpace) {
  84985. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  84986. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  84987. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  84988. }
  84989. // Convert to int texture for fallback.
  84990. if (byteArray) {
  84991. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  84992. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  84993. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  84994. // May use luminance instead if the result is not accurate.
  84995. var max = Math.max(Math.max(r, g), b);
  84996. if (max > 255) {
  84997. var scale = 255 / max;
  84998. r *= scale;
  84999. g *= scale;
  85000. b *= scale;
  85001. }
  85002. byteArray[(i * 3) + 0] = r;
  85003. byteArray[(i * 3) + 1] = g;
  85004. byteArray[(i * 3) + 2] = b;
  85005. }
  85006. }
  85007. }
  85008. if (byteArray) {
  85009. results.push(byteArray);
  85010. }
  85011. else {
  85012. results.push(dataFace);
  85013. }
  85014. }
  85015. return results;
  85016. };
  85017. var scene = this.getScene();
  85018. if (scene) {
  85019. 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);
  85020. }
  85021. };
  85022. HDRCubeTexture.prototype.clone = function () {
  85023. var scene = this.getScene();
  85024. if (!scene) {
  85025. return this;
  85026. }
  85027. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85028. // Base texture
  85029. newTexture.level = this.level;
  85030. newTexture.wrapU = this.wrapU;
  85031. newTexture.wrapV = this.wrapV;
  85032. newTexture.coordinatesIndex = this.coordinatesIndex;
  85033. newTexture.coordinatesMode = this.coordinatesMode;
  85034. return newTexture;
  85035. };
  85036. // Methods
  85037. HDRCubeTexture.prototype.delayLoad = function () {
  85038. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85039. return;
  85040. }
  85041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85042. this._texture = this._getFromCache(this.url, this._noMipmap);
  85043. if (!this._texture) {
  85044. this.loadTexture();
  85045. }
  85046. };
  85047. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85048. return this._textureMatrix;
  85049. };
  85050. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85051. this._textureMatrix = value;
  85052. };
  85053. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85054. var texture = null;
  85055. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85056. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85057. texture.name = parsedTexture.name;
  85058. texture.hasAlpha = parsedTexture.hasAlpha;
  85059. texture.level = parsedTexture.level;
  85060. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85061. texture.isBlocking = parsedTexture.isBlocking;
  85062. }
  85063. if (texture) {
  85064. if (parsedTexture.boundingBoxPosition) {
  85065. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85066. }
  85067. if (parsedTexture.boundingBoxSize) {
  85068. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85069. }
  85070. if (parsedTexture.rotationY) {
  85071. texture.rotationY = parsedTexture.rotationY;
  85072. }
  85073. }
  85074. return texture;
  85075. };
  85076. HDRCubeTexture.prototype.serialize = function () {
  85077. if (!this.name) {
  85078. return null;
  85079. }
  85080. var serializationObject = {};
  85081. serializationObject.name = this.name;
  85082. serializationObject.hasAlpha = this.hasAlpha;
  85083. serializationObject.isCube = true;
  85084. serializationObject.level = this.level;
  85085. serializationObject.size = this._size;
  85086. serializationObject.coordinatesMode = this.coordinatesMode;
  85087. serializationObject.useInGammaSpace = this.gammaSpace;
  85088. serializationObject.generateHarmonics = this._generateHarmonics;
  85089. serializationObject.customType = "BABYLON.HDRCubeTexture";
  85090. serializationObject.noMipmap = this._noMipmap;
  85091. serializationObject.isBlocking = this._isBlocking;
  85092. serializationObject.rotationY = this._rotationY;
  85093. return serializationObject;
  85094. };
  85095. HDRCubeTexture._facesMapping = [
  85096. "right",
  85097. "left",
  85098. "up",
  85099. "down",
  85100. "front",
  85101. "back"
  85102. ];
  85103. return HDRCubeTexture;
  85104. }(BABYLON.BaseTexture));
  85105. BABYLON.HDRCubeTexture = HDRCubeTexture;
  85106. })(BABYLON || (BABYLON = {}));
  85107. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  85108. var BABYLON;
  85109. (function (BABYLON) {
  85110. /**
  85111. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  85112. */
  85113. var PanoramaToCubeMapTools = /** @class */ (function () {
  85114. function PanoramaToCubeMapTools() {
  85115. }
  85116. /**
  85117. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  85118. *
  85119. * @param float32Array The source data.
  85120. * @param inputWidth The width of the input panorama.
  85121. * @param inputhHeight The height of the input panorama.
  85122. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  85123. * @return The cubemap data
  85124. */
  85125. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  85126. if (!float32Array) {
  85127. throw "ConvertPanoramaToCubemap: input cannot be null";
  85128. }
  85129. if (float32Array.length != inputWidth * inputHeight * 3) {
  85130. throw "ConvertPanoramaToCubemap: input size is wrong";
  85131. }
  85132. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  85133. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  85134. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  85135. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  85136. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  85137. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  85138. return {
  85139. front: textureFront,
  85140. back: textureBack,
  85141. left: textureLeft,
  85142. right: textureRight,
  85143. up: textureUp,
  85144. down: textureDown,
  85145. size: size,
  85146. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85147. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  85148. gammaSpace: false,
  85149. };
  85150. };
  85151. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  85152. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  85153. var textureArray = new Float32Array(buffer);
  85154. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  85155. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  85156. var dy = 1 / texSize;
  85157. var fy = 0;
  85158. for (var y = 0; y < texSize; y++) {
  85159. var xv1 = faceData[0];
  85160. var xv2 = faceData[2];
  85161. for (var x = 0; x < texSize; x++) {
  85162. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  85163. v.normalize();
  85164. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  85165. // 3 channels per pixels
  85166. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  85167. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  85168. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  85169. xv1 = xv1.add(rotDX1);
  85170. xv2 = xv2.add(rotDX2);
  85171. }
  85172. fy += dy;
  85173. }
  85174. return textureArray;
  85175. };
  85176. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  85177. var theta = Math.atan2(vDir.z, vDir.x);
  85178. var phi = Math.acos(vDir.y);
  85179. while (theta < -Math.PI)
  85180. theta += 2 * Math.PI;
  85181. while (theta > Math.PI)
  85182. theta -= 2 * Math.PI;
  85183. var dx = theta / Math.PI;
  85184. var dy = phi / Math.PI;
  85185. // recenter.
  85186. dx = dx * 0.5 + 0.5;
  85187. var px = Math.round(dx * inputWidth);
  85188. if (px < 0)
  85189. px = 0;
  85190. else if (px >= inputWidth)
  85191. px = inputWidth - 1;
  85192. var py = Math.round(dy * inputHeight);
  85193. if (py < 0)
  85194. py = 0;
  85195. else if (py >= inputHeight)
  85196. py = inputHeight - 1;
  85197. var inputY = (inputHeight - py - 1);
  85198. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  85199. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  85200. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  85201. return {
  85202. r: r,
  85203. g: g,
  85204. b: b
  85205. };
  85206. };
  85207. PanoramaToCubeMapTools.FACE_FRONT = [
  85208. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85209. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85210. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85211. new BABYLON.Vector3(1.0, 1.0, -1.0)
  85212. ];
  85213. PanoramaToCubeMapTools.FACE_BACK = [
  85214. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85215. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85216. new BABYLON.Vector3(1.0, 1.0, 1.0),
  85217. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  85218. ];
  85219. PanoramaToCubeMapTools.FACE_RIGHT = [
  85220. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85221. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85222. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85223. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85224. ];
  85225. PanoramaToCubeMapTools.FACE_LEFT = [
  85226. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85227. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85228. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85229. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  85230. ];
  85231. PanoramaToCubeMapTools.FACE_DOWN = [
  85232. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85233. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85234. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85235. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85236. ];
  85237. PanoramaToCubeMapTools.FACE_UP = [
  85238. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85239. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85240. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85241. new BABYLON.Vector3(1.0, -1.0, -1.0)
  85242. ];
  85243. return PanoramaToCubeMapTools;
  85244. }());
  85245. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85246. })(BABYLON || (BABYLON = {}));
  85247. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85248. var BABYLON;
  85249. (function (BABYLON) {
  85250. var IndexedVector2 = /** @class */ (function (_super) {
  85251. __extends(IndexedVector2, _super);
  85252. function IndexedVector2(original, index) {
  85253. var _this = _super.call(this, original.x, original.y) || this;
  85254. _this.index = index;
  85255. return _this;
  85256. }
  85257. return IndexedVector2;
  85258. }(BABYLON.Vector2));
  85259. var PolygonPoints = /** @class */ (function () {
  85260. function PolygonPoints() {
  85261. this.elements = new Array();
  85262. }
  85263. PolygonPoints.prototype.add = function (originalPoints) {
  85264. var _this = this;
  85265. var result = new Array();
  85266. originalPoints.forEach(function (point) {
  85267. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85268. var newPoint = new IndexedVector2(point, _this.elements.length);
  85269. result.push(newPoint);
  85270. _this.elements.push(newPoint);
  85271. }
  85272. });
  85273. return result;
  85274. };
  85275. PolygonPoints.prototype.computeBounds = function () {
  85276. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85277. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85278. this.elements.forEach(function (point) {
  85279. // x
  85280. if (point.x < lmin.x) {
  85281. lmin.x = point.x;
  85282. }
  85283. else if (point.x > lmax.x) {
  85284. lmax.x = point.x;
  85285. }
  85286. // y
  85287. if (point.y < lmin.y) {
  85288. lmin.y = point.y;
  85289. }
  85290. else if (point.y > lmax.y) {
  85291. lmax.y = point.y;
  85292. }
  85293. });
  85294. return {
  85295. min: lmin,
  85296. max: lmax,
  85297. width: lmax.x - lmin.x,
  85298. height: lmax.y - lmin.y
  85299. };
  85300. };
  85301. return PolygonPoints;
  85302. }());
  85303. var Polygon = /** @class */ (function () {
  85304. function Polygon() {
  85305. }
  85306. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85307. return [
  85308. new BABYLON.Vector2(xmin, ymin),
  85309. new BABYLON.Vector2(xmax, ymin),
  85310. new BABYLON.Vector2(xmax, ymax),
  85311. new BABYLON.Vector2(xmin, ymax)
  85312. ];
  85313. };
  85314. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85315. if (cx === void 0) { cx = 0; }
  85316. if (cy === void 0) { cy = 0; }
  85317. if (numberOfSides === void 0) { numberOfSides = 32; }
  85318. var result = new Array();
  85319. var angle = 0;
  85320. var increment = (Math.PI * 2) / numberOfSides;
  85321. for (var i = 0; i < numberOfSides; i++) {
  85322. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85323. angle -= increment;
  85324. }
  85325. return result;
  85326. };
  85327. Polygon.Parse = function (input) {
  85328. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85329. var i, result = [];
  85330. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85331. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85332. }
  85333. return result;
  85334. };
  85335. Polygon.StartingAt = function (x, y) {
  85336. return BABYLON.Path2.StartingAt(x, y);
  85337. };
  85338. return Polygon;
  85339. }());
  85340. BABYLON.Polygon = Polygon;
  85341. var PolygonMeshBuilder = /** @class */ (function () {
  85342. function PolygonMeshBuilder(name, contours, scene) {
  85343. this._points = new PolygonPoints();
  85344. this._outlinepoints = new PolygonPoints();
  85345. this._holes = new Array();
  85346. this._epoints = new Array();
  85347. this._eholes = new Array();
  85348. this._name = name;
  85349. this._scene = scene;
  85350. var points;
  85351. if (contours instanceof BABYLON.Path2) {
  85352. points = contours.getPoints();
  85353. }
  85354. else {
  85355. points = contours;
  85356. }
  85357. this._addToepoint(points);
  85358. this._points.add(points);
  85359. this._outlinepoints.add(points);
  85360. if (typeof earcut === 'undefined') {
  85361. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85362. }
  85363. }
  85364. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85365. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85366. var p = points_1[_i];
  85367. this._epoints.push(p.x, p.y);
  85368. }
  85369. };
  85370. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85371. this._points.add(hole);
  85372. var holepoints = new PolygonPoints();
  85373. holepoints.add(hole);
  85374. this._holes.push(holepoints);
  85375. this._eholes.push(this._epoints.length / 2);
  85376. this._addToepoint(hole);
  85377. return this;
  85378. };
  85379. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85380. var _this = this;
  85381. if (updatable === void 0) { updatable = false; }
  85382. if (depth === void 0) { depth = 0; }
  85383. var result = new BABYLON.Mesh(this._name, this._scene);
  85384. var normals = new Array();
  85385. var positions = new Array();
  85386. var uvs = new Array();
  85387. var bounds = this._points.computeBounds();
  85388. this._points.elements.forEach(function (p) {
  85389. normals.push(0, 1.0, 0);
  85390. positions.push(p.x, 0, p.y);
  85391. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85392. });
  85393. var indices = new Array();
  85394. var res = earcut(this._epoints, this._eholes, 2);
  85395. for (var i = 0; i < res.length; i++) {
  85396. indices.push(res[i]);
  85397. }
  85398. if (depth > 0) {
  85399. var positionscount = (positions.length / 3); //get the current pointcount
  85400. this._points.elements.forEach(function (p) {
  85401. normals.push(0, -1.0, 0);
  85402. positions.push(p.x, -depth, p.y);
  85403. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85404. });
  85405. var totalCount = indices.length;
  85406. for (var i = 0; i < totalCount; i += 3) {
  85407. var i0 = indices[i + 0];
  85408. var i1 = indices[i + 1];
  85409. var i2 = indices[i + 2];
  85410. indices.push(i2 + positionscount);
  85411. indices.push(i1 + positionscount);
  85412. indices.push(i0 + positionscount);
  85413. }
  85414. //Add the sides
  85415. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85416. this._holes.forEach(function (hole) {
  85417. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85418. });
  85419. }
  85420. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85421. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85422. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85423. result.setIndices(indices);
  85424. return result;
  85425. };
  85426. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85427. var StartIndex = positions.length / 3;
  85428. var ulength = 0;
  85429. for (var i = 0; i < points.elements.length; i++) {
  85430. var p = points.elements[i];
  85431. var p1;
  85432. if ((i + 1) > points.elements.length - 1) {
  85433. p1 = points.elements[0];
  85434. }
  85435. else {
  85436. p1 = points.elements[i + 1];
  85437. }
  85438. positions.push(p.x, 0, p.y);
  85439. positions.push(p.x, -depth, p.y);
  85440. positions.push(p1.x, 0, p1.y);
  85441. positions.push(p1.x, -depth, p1.y);
  85442. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85443. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85444. var v3 = v2.subtract(v1);
  85445. var v4 = new BABYLON.Vector3(0, 1, 0);
  85446. var vn = BABYLON.Vector3.Cross(v3, v4);
  85447. vn = vn.normalize();
  85448. uvs.push(ulength / bounds.width, 0);
  85449. uvs.push(ulength / bounds.width, 1);
  85450. ulength += v3.length();
  85451. uvs.push((ulength / bounds.width), 0);
  85452. uvs.push((ulength / bounds.width), 1);
  85453. if (!flip) {
  85454. normals.push(-vn.x, -vn.y, -vn.z);
  85455. normals.push(-vn.x, -vn.y, -vn.z);
  85456. normals.push(-vn.x, -vn.y, -vn.z);
  85457. normals.push(-vn.x, -vn.y, -vn.z);
  85458. indices.push(StartIndex);
  85459. indices.push(StartIndex + 1);
  85460. indices.push(StartIndex + 2);
  85461. indices.push(StartIndex + 1);
  85462. indices.push(StartIndex + 3);
  85463. indices.push(StartIndex + 2);
  85464. }
  85465. else {
  85466. normals.push(vn.x, vn.y, vn.z);
  85467. normals.push(vn.x, vn.y, vn.z);
  85468. normals.push(vn.x, vn.y, vn.z);
  85469. normals.push(vn.x, vn.y, vn.z);
  85470. indices.push(StartIndex);
  85471. indices.push(StartIndex + 2);
  85472. indices.push(StartIndex + 1);
  85473. indices.push(StartIndex + 1);
  85474. indices.push(StartIndex + 2);
  85475. indices.push(StartIndex + 3);
  85476. }
  85477. StartIndex += 4;
  85478. }
  85479. ;
  85480. };
  85481. return PolygonMeshBuilder;
  85482. }());
  85483. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85484. })(BABYLON || (BABYLON = {}));
  85485. //# sourceMappingURL=babylon.polygonMesh.js.map
  85486. var BABYLON;
  85487. (function (BABYLON) {
  85488. // Unique ID when we import meshes from Babylon to CSG
  85489. var currentCSGMeshId = 0;
  85490. // # class Vertex
  85491. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85492. // one to provide additional features like texture coordinates and vertex
  85493. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85494. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85495. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85496. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85497. // is not used anywhere else.
  85498. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85499. var Vertex = /** @class */ (function () {
  85500. function Vertex(pos, normal, uv) {
  85501. this.pos = pos;
  85502. this.normal = normal;
  85503. this.uv = uv;
  85504. }
  85505. Vertex.prototype.clone = function () {
  85506. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85507. };
  85508. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85509. // orientation of a polygon is flipped.
  85510. Vertex.prototype.flip = function () {
  85511. this.normal = this.normal.scale(-1);
  85512. };
  85513. // Create a new vertex between this vertex and `other` by linearly
  85514. // interpolating all properties using a parameter of `t`. Subclasses should
  85515. // override this to interpolate additional properties.
  85516. Vertex.prototype.interpolate = function (other, t) {
  85517. 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));
  85518. };
  85519. return Vertex;
  85520. }());
  85521. // # class Plane
  85522. // Represents a plane in 3D space.
  85523. var Plane = /** @class */ (function () {
  85524. function Plane(normal, w) {
  85525. this.normal = normal;
  85526. this.w = w;
  85527. }
  85528. Plane.FromPoints = function (a, b, c) {
  85529. var v0 = c.subtract(a);
  85530. var v1 = b.subtract(a);
  85531. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  85532. return null;
  85533. }
  85534. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  85535. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  85536. };
  85537. Plane.prototype.clone = function () {
  85538. return new Plane(this.normal.clone(), this.w);
  85539. };
  85540. Plane.prototype.flip = function () {
  85541. this.normal.scaleInPlace(-1);
  85542. this.w = -this.w;
  85543. };
  85544. // Split `polygon` by this plane if needed, then put the polygon or polygon
  85545. // fragments in the appropriate lists. Coplanar polygons go into either
  85546. // `coplanarFront` or `coplanarBack` depending on their orientation with
  85547. // respect to this plane. Polygons in front or in back of this plane go into
  85548. // either `front` or `back`.
  85549. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  85550. var COPLANAR = 0;
  85551. var FRONT = 1;
  85552. var BACK = 2;
  85553. var SPANNING = 3;
  85554. // Classify each point as well as the entire polygon into one of the above
  85555. // four classes.
  85556. var polygonType = 0;
  85557. var types = [];
  85558. var i;
  85559. var t;
  85560. for (i = 0; i < polygon.vertices.length; i++) {
  85561. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  85562. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  85563. polygonType |= type;
  85564. types.push(type);
  85565. }
  85566. // Put the polygon in the correct list, splitting it when necessary.
  85567. switch (polygonType) {
  85568. case COPLANAR:
  85569. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  85570. break;
  85571. case FRONT:
  85572. front.push(polygon);
  85573. break;
  85574. case BACK:
  85575. back.push(polygon);
  85576. break;
  85577. case SPANNING:
  85578. var f = [], b = [];
  85579. for (i = 0; i < polygon.vertices.length; i++) {
  85580. var j = (i + 1) % polygon.vertices.length;
  85581. var ti = types[i], tj = types[j];
  85582. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  85583. if (ti !== BACK)
  85584. f.push(vi);
  85585. if (ti !== FRONT)
  85586. b.push(ti !== BACK ? vi.clone() : vi);
  85587. if ((ti | tj) === SPANNING) {
  85588. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  85589. var v = vi.interpolate(vj, t);
  85590. f.push(v);
  85591. b.push(v.clone());
  85592. }
  85593. }
  85594. var poly;
  85595. if (f.length >= 3) {
  85596. poly = new Polygon(f, polygon.shared);
  85597. if (poly.plane)
  85598. front.push(poly);
  85599. }
  85600. if (b.length >= 3) {
  85601. poly = new Polygon(b, polygon.shared);
  85602. if (poly.plane)
  85603. back.push(poly);
  85604. }
  85605. break;
  85606. }
  85607. };
  85608. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  85609. // point is on the plane.
  85610. Plane.EPSILON = 1e-5;
  85611. return Plane;
  85612. }());
  85613. // # class Polygon
  85614. // Represents a convex polygon. The vertices used to initialize a polygon must
  85615. // be coplanar and form a convex loop.
  85616. //
  85617. // Each convex polygon has a `shared` property, which is shared between all
  85618. // polygons that are clones of each other or were split from the same polygon.
  85619. // This can be used to define per-polygon properties (such as surface color).
  85620. var Polygon = /** @class */ (function () {
  85621. function Polygon(vertices, shared) {
  85622. this.vertices = vertices;
  85623. this.shared = shared;
  85624. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  85625. }
  85626. Polygon.prototype.clone = function () {
  85627. var vertices = this.vertices.map(function (v) { return v.clone(); });
  85628. return new Polygon(vertices, this.shared);
  85629. };
  85630. Polygon.prototype.flip = function () {
  85631. this.vertices.reverse().map(function (v) { v.flip(); });
  85632. this.plane.flip();
  85633. };
  85634. return Polygon;
  85635. }());
  85636. // # class Node
  85637. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  85638. // by picking a polygon to split along. That polygon (and all other coplanar
  85639. // polygons) are added directly to that node and the other polygons are added to
  85640. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  85641. // no distinction between internal and leaf nodes.
  85642. var Node = /** @class */ (function () {
  85643. function Node(polygons) {
  85644. this.plane = null;
  85645. this.front = null;
  85646. this.back = null;
  85647. this.polygons = new Array();
  85648. if (polygons) {
  85649. this.build(polygons);
  85650. }
  85651. }
  85652. Node.prototype.clone = function () {
  85653. var node = new Node();
  85654. node.plane = this.plane && this.plane.clone();
  85655. node.front = this.front && this.front.clone();
  85656. node.back = this.back && this.back.clone();
  85657. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  85658. return node;
  85659. };
  85660. // Convert solid space to empty space and empty space to solid space.
  85661. Node.prototype.invert = function () {
  85662. for (var i = 0; i < this.polygons.length; i++) {
  85663. this.polygons[i].flip();
  85664. }
  85665. if (this.plane) {
  85666. this.plane.flip();
  85667. }
  85668. if (this.front) {
  85669. this.front.invert();
  85670. }
  85671. if (this.back) {
  85672. this.back.invert();
  85673. }
  85674. var temp = this.front;
  85675. this.front = this.back;
  85676. this.back = temp;
  85677. };
  85678. // Recursively remove all polygons in `polygons` that are inside this BSP
  85679. // tree.
  85680. Node.prototype.clipPolygons = function (polygons) {
  85681. if (!this.plane)
  85682. return polygons.slice();
  85683. var front = new Array(), back = new Array();
  85684. for (var i = 0; i < polygons.length; i++) {
  85685. this.plane.splitPolygon(polygons[i], front, back, front, back);
  85686. }
  85687. if (this.front) {
  85688. front = this.front.clipPolygons(front);
  85689. }
  85690. if (this.back) {
  85691. back = this.back.clipPolygons(back);
  85692. }
  85693. else {
  85694. back = [];
  85695. }
  85696. return front.concat(back);
  85697. };
  85698. // Remove all polygons in this BSP tree that are inside the other BSP tree
  85699. // `bsp`.
  85700. Node.prototype.clipTo = function (bsp) {
  85701. this.polygons = bsp.clipPolygons(this.polygons);
  85702. if (this.front)
  85703. this.front.clipTo(bsp);
  85704. if (this.back)
  85705. this.back.clipTo(bsp);
  85706. };
  85707. // Return a list of all polygons in this BSP tree.
  85708. Node.prototype.allPolygons = function () {
  85709. var polygons = this.polygons.slice();
  85710. if (this.front)
  85711. polygons = polygons.concat(this.front.allPolygons());
  85712. if (this.back)
  85713. polygons = polygons.concat(this.back.allPolygons());
  85714. return polygons;
  85715. };
  85716. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  85717. // new polygons are filtered down to the bottom of the tree and become new
  85718. // nodes there. Each set of polygons is partitioned using the first polygon
  85719. // (no heuristic is used to pick a good split).
  85720. Node.prototype.build = function (polygons) {
  85721. if (!polygons.length)
  85722. return;
  85723. if (!this.plane)
  85724. this.plane = polygons[0].plane.clone();
  85725. var front = new Array(), back = new Array();
  85726. for (var i = 0; i < polygons.length; i++) {
  85727. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  85728. }
  85729. if (front.length) {
  85730. if (!this.front)
  85731. this.front = new Node();
  85732. this.front.build(front);
  85733. }
  85734. if (back.length) {
  85735. if (!this.back)
  85736. this.back = new Node();
  85737. this.back.build(back);
  85738. }
  85739. };
  85740. return Node;
  85741. }());
  85742. var CSG = /** @class */ (function () {
  85743. function CSG() {
  85744. this.polygons = new Array();
  85745. }
  85746. // Convert BABYLON.Mesh to BABYLON.CSG
  85747. CSG.FromMesh = function (mesh) {
  85748. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  85749. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  85750. if (mesh instanceof BABYLON.Mesh) {
  85751. mesh.computeWorldMatrix(true);
  85752. matrix = mesh.getWorldMatrix();
  85753. meshPosition = mesh.position.clone();
  85754. meshRotation = mesh.rotation.clone();
  85755. if (mesh.rotationQuaternion) {
  85756. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  85757. }
  85758. meshScaling = mesh.scaling.clone();
  85759. }
  85760. else {
  85761. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  85762. }
  85763. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85764. var subMeshes = mesh.subMeshes;
  85765. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  85766. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  85767. vertices = [];
  85768. for (var j = 0; j < 3; j++) {
  85769. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  85770. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  85771. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  85772. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  85773. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  85774. vertex = new Vertex(position, normal, uv);
  85775. vertices.push(vertex);
  85776. }
  85777. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  85778. // To handle the case of degenerated triangle
  85779. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  85780. if (polygon.plane)
  85781. polygons.push(polygon);
  85782. }
  85783. }
  85784. var csg = CSG.FromPolygons(polygons);
  85785. csg.matrix = matrix;
  85786. csg.position = meshPosition;
  85787. csg.rotation = meshRotation;
  85788. csg.scaling = meshScaling;
  85789. csg.rotationQuaternion = meshRotationQuaternion;
  85790. currentCSGMeshId++;
  85791. return csg;
  85792. };
  85793. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  85794. CSG.FromPolygons = function (polygons) {
  85795. var csg = new CSG();
  85796. csg.polygons = polygons;
  85797. return csg;
  85798. };
  85799. CSG.prototype.clone = function () {
  85800. var csg = new CSG();
  85801. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  85802. csg.copyTransformAttributes(this);
  85803. return csg;
  85804. };
  85805. CSG.prototype.union = function (csg) {
  85806. var a = new Node(this.clone().polygons);
  85807. var b = new Node(csg.clone().polygons);
  85808. a.clipTo(b);
  85809. b.clipTo(a);
  85810. b.invert();
  85811. b.clipTo(a);
  85812. b.invert();
  85813. a.build(b.allPolygons());
  85814. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85815. };
  85816. CSG.prototype.unionInPlace = function (csg) {
  85817. var a = new Node(this.polygons);
  85818. var b = new Node(csg.polygons);
  85819. a.clipTo(b);
  85820. b.clipTo(a);
  85821. b.invert();
  85822. b.clipTo(a);
  85823. b.invert();
  85824. a.build(b.allPolygons());
  85825. this.polygons = a.allPolygons();
  85826. };
  85827. CSG.prototype.subtract = function (csg) {
  85828. var a = new Node(this.clone().polygons);
  85829. var b = new Node(csg.clone().polygons);
  85830. a.invert();
  85831. a.clipTo(b);
  85832. b.clipTo(a);
  85833. b.invert();
  85834. b.clipTo(a);
  85835. b.invert();
  85836. a.build(b.allPolygons());
  85837. a.invert();
  85838. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85839. };
  85840. CSG.prototype.subtractInPlace = function (csg) {
  85841. var a = new Node(this.polygons);
  85842. var b = new Node(csg.polygons);
  85843. a.invert();
  85844. a.clipTo(b);
  85845. b.clipTo(a);
  85846. b.invert();
  85847. b.clipTo(a);
  85848. b.invert();
  85849. a.build(b.allPolygons());
  85850. a.invert();
  85851. this.polygons = a.allPolygons();
  85852. };
  85853. CSG.prototype.intersect = function (csg) {
  85854. var a = new Node(this.clone().polygons);
  85855. var b = new Node(csg.clone().polygons);
  85856. a.invert();
  85857. b.clipTo(a);
  85858. b.invert();
  85859. a.clipTo(b);
  85860. b.clipTo(a);
  85861. a.build(b.allPolygons());
  85862. a.invert();
  85863. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85864. };
  85865. CSG.prototype.intersectInPlace = function (csg) {
  85866. var a = new Node(this.polygons);
  85867. var b = new Node(csg.polygons);
  85868. a.invert();
  85869. b.clipTo(a);
  85870. b.invert();
  85871. a.clipTo(b);
  85872. b.clipTo(a);
  85873. a.build(b.allPolygons());
  85874. a.invert();
  85875. this.polygons = a.allPolygons();
  85876. };
  85877. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  85878. // not modified.
  85879. CSG.prototype.inverse = function () {
  85880. var csg = this.clone();
  85881. csg.inverseInPlace();
  85882. return csg;
  85883. };
  85884. CSG.prototype.inverseInPlace = function () {
  85885. this.polygons.map(function (p) { p.flip(); });
  85886. };
  85887. // This is used to keep meshes transformations so they can be restored
  85888. // when we build back a Babylon Mesh
  85889. // NB : All CSG operations are performed in world coordinates
  85890. CSG.prototype.copyTransformAttributes = function (csg) {
  85891. this.matrix = csg.matrix;
  85892. this.position = csg.position;
  85893. this.rotation = csg.rotation;
  85894. this.scaling = csg.scaling;
  85895. this.rotationQuaternion = csg.rotationQuaternion;
  85896. return this;
  85897. };
  85898. // Build Raw mesh from CSG
  85899. // Coordinates here are in world space
  85900. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  85901. var matrix = this.matrix.clone();
  85902. matrix.invert();
  85903. 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;
  85904. if (keepSubMeshes) {
  85905. // Sort Polygons, since subMeshes are indices range
  85906. polygons.sort(function (a, b) {
  85907. if (a.shared.meshId === b.shared.meshId) {
  85908. return a.shared.subMeshId - b.shared.subMeshId;
  85909. }
  85910. else {
  85911. return a.shared.meshId - b.shared.meshId;
  85912. }
  85913. });
  85914. }
  85915. for (var i = 0, il = polygons.length; i < il; i++) {
  85916. polygon = polygons[i];
  85917. // Building SubMeshes
  85918. if (!subMesh_dict[polygon.shared.meshId]) {
  85919. subMesh_dict[polygon.shared.meshId] = {};
  85920. }
  85921. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  85922. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  85923. indexStart: +Infinity,
  85924. indexEnd: -Infinity,
  85925. materialIndex: polygon.shared.materialIndex
  85926. };
  85927. }
  85928. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  85929. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  85930. polygonIndices[0] = 0;
  85931. polygonIndices[1] = j - 1;
  85932. polygonIndices[2] = j;
  85933. for (var k = 0; k < 3; k++) {
  85934. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  85935. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  85936. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  85937. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  85938. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  85939. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  85940. // Check if 2 points can be merged
  85941. if (!(typeof vertex_idx !== 'undefined' &&
  85942. normals[vertex_idx * 3] === localNormal.x &&
  85943. normals[vertex_idx * 3 + 1] === localNormal.y &&
  85944. normals[vertex_idx * 3 + 2] === localNormal.z &&
  85945. uvs[vertex_idx * 2] === uv.x &&
  85946. uvs[vertex_idx * 2 + 1] === uv.y)) {
  85947. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  85948. uvs.push(uv.x, uv.y);
  85949. normals.push(normal.x, normal.y, normal.z);
  85950. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  85951. }
  85952. indices.push(vertex_idx);
  85953. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  85954. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  85955. currentIndex++;
  85956. }
  85957. }
  85958. }
  85959. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  85960. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  85961. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  85962. mesh.setIndices(indices, null);
  85963. if (keepSubMeshes) {
  85964. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  85965. var materialIndexOffset = 0, materialMaxIndex;
  85966. mesh.subMeshes = new Array();
  85967. for (var m in subMesh_dict) {
  85968. materialMaxIndex = -1;
  85969. for (var sm in subMesh_dict[m]) {
  85970. subMesh_obj = subMesh_dict[m][sm];
  85971. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  85972. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  85973. }
  85974. materialIndexOffset += ++materialMaxIndex;
  85975. }
  85976. }
  85977. return mesh;
  85978. };
  85979. // Build Mesh from CSG taking material and transforms into account
  85980. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  85981. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  85982. mesh.material = material;
  85983. mesh.position.copyFrom(this.position);
  85984. mesh.rotation.copyFrom(this.rotation);
  85985. if (this.rotationQuaternion) {
  85986. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  85987. }
  85988. mesh.scaling.copyFrom(this.scaling);
  85989. mesh.computeWorldMatrix(true);
  85990. return mesh;
  85991. };
  85992. return CSG;
  85993. }());
  85994. BABYLON.CSG = CSG;
  85995. })(BABYLON || (BABYLON = {}));
  85996. //# sourceMappingURL=babylon.csg.js.map
  85997. var BABYLON;
  85998. (function (BABYLON) {
  85999. var LensFlare = /** @class */ (function () {
  86000. function LensFlare(size, position, color, imgUrl, system) {
  86001. this.size = size;
  86002. this.position = position;
  86003. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86004. this.color = color || new BABYLON.Color3(1, 1, 1);
  86005. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86006. this._system = system;
  86007. system.lensFlares.push(this);
  86008. }
  86009. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86010. return new LensFlare(size, position, color, imgUrl, system);
  86011. };
  86012. LensFlare.prototype.dispose = function () {
  86013. if (this.texture) {
  86014. this.texture.dispose();
  86015. }
  86016. // Remove from scene
  86017. var index = this._system.lensFlares.indexOf(this);
  86018. this._system.lensFlares.splice(index, 1);
  86019. };
  86020. ;
  86021. return LensFlare;
  86022. }());
  86023. BABYLON.LensFlare = LensFlare;
  86024. })(BABYLON || (BABYLON = {}));
  86025. //# sourceMappingURL=babylon.lensFlare.js.map
  86026. var BABYLON;
  86027. (function (BABYLON) {
  86028. // Adds the parser to the scene parsers.
  86029. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86030. // Lens flares
  86031. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86032. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86033. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86034. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86035. container.lensFlareSystems.push(lf);
  86036. }
  86037. }
  86038. });
  86039. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86040. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86041. if (this.lensFlareSystems[index].name === name) {
  86042. return this.lensFlareSystems[index];
  86043. }
  86044. }
  86045. return null;
  86046. };
  86047. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86048. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86049. if (this.lensFlareSystems[index].id === id) {
  86050. return this.lensFlareSystems[index];
  86051. }
  86052. }
  86053. return null;
  86054. };
  86055. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86056. var index = this.lensFlareSystems.indexOf(toRemove);
  86057. if (index !== -1) {
  86058. this.lensFlareSystems.splice(index, 1);
  86059. }
  86060. return index;
  86061. };
  86062. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86063. this.lensFlareSystems.push(newLensFlareSystem);
  86064. };
  86065. /**
  86066. * Defines the lens flare scene component responsible to manage any lens flares
  86067. * in a given scene.
  86068. */
  86069. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86070. /**
  86071. * Creates a new instance of the component for the given scene
  86072. * @param scene Defines the scene to register the component in
  86073. */
  86074. function LensFlareSystemSceneComponent(scene) {
  86075. /**
  86076. * The component name helpfull to identify the component in the list of scene components.
  86077. */
  86078. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86079. this.scene = scene;
  86080. scene.lensFlareSystems = new Array();
  86081. }
  86082. /**
  86083. * Registers the component in a given scene
  86084. */
  86085. LensFlareSystemSceneComponent.prototype.register = function () {
  86086. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  86087. };
  86088. /**
  86089. * Rebuilds the elements related to this component in case of
  86090. * context lost for instance.
  86091. */
  86092. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  86093. // Nothing to do for lens flare
  86094. };
  86095. /**
  86096. * Adds all the element from the container to the scene
  86097. * @param container the container holding the elements
  86098. */
  86099. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  86100. var _this = this;
  86101. if (!container.lensFlareSystems) {
  86102. return;
  86103. }
  86104. container.lensFlareSystems.forEach(function (o) {
  86105. _this.scene.addLensFlareSystem(o);
  86106. });
  86107. };
  86108. /**
  86109. * Removes all the elements in the container from the scene
  86110. * @param container contains the elements to remove
  86111. */
  86112. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  86113. var _this = this;
  86114. if (!container.lensFlareSystems) {
  86115. return;
  86116. }
  86117. container.lensFlareSystems.forEach(function (o) {
  86118. _this.scene.removeLensFlareSystem(o);
  86119. });
  86120. };
  86121. /**
  86122. * Serializes the component data to the specified json object
  86123. * @param serializationObject The object to serialize to
  86124. */
  86125. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  86126. // Lens flares
  86127. serializationObject.lensFlareSystems = [];
  86128. var lensFlareSystems = this.scene.lensFlareSystems;
  86129. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  86130. var lensFlareSystem = lensFlareSystems_1[_i];
  86131. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  86132. }
  86133. };
  86134. /**
  86135. * Disposes the component and the associated ressources.
  86136. */
  86137. LensFlareSystemSceneComponent.prototype.dispose = function () {
  86138. var lensFlareSystems = this.scene.lensFlareSystems;
  86139. while (lensFlareSystems.length) {
  86140. lensFlareSystems[0].dispose();
  86141. }
  86142. };
  86143. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  86144. // Lens flares
  86145. if (this.scene.lensFlaresEnabled) {
  86146. var lensFlareSystems = this.scene.lensFlareSystems;
  86147. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86148. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  86149. var lensFlareSystem = lensFlareSystems_2[_i];
  86150. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  86151. lensFlareSystem.render();
  86152. }
  86153. }
  86154. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86155. }
  86156. };
  86157. return LensFlareSystemSceneComponent;
  86158. }());
  86159. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  86160. })(BABYLON || (BABYLON = {}));
  86161. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  86162. var BABYLON;
  86163. (function (BABYLON) {
  86164. var LensFlareSystem = /** @class */ (function () {
  86165. function LensFlareSystem(name, emitter, scene) {
  86166. this.name = name;
  86167. this.lensFlares = new Array();
  86168. this.borderLimit = 300;
  86169. this.viewportBorder = 0;
  86170. this.layerMask = 0x0FFFFFFF;
  86171. this._vertexBuffers = {};
  86172. this._isEnabled = true;
  86173. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86174. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  86175. if (!component) {
  86176. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  86177. scene._addComponent(component);
  86178. }
  86179. this._emitter = emitter;
  86180. this.id = name;
  86181. scene.lensFlareSystems.push(this);
  86182. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  86183. var engine = scene.getEngine();
  86184. // VBO
  86185. var vertices = [];
  86186. vertices.push(1, 1);
  86187. vertices.push(-1, 1);
  86188. vertices.push(-1, -1);
  86189. vertices.push(1, -1);
  86190. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86191. // Indices
  86192. var indices = [];
  86193. indices.push(0);
  86194. indices.push(1);
  86195. indices.push(2);
  86196. indices.push(0);
  86197. indices.push(2);
  86198. indices.push(3);
  86199. this._indexBuffer = engine.createIndexBuffer(indices);
  86200. // Effects
  86201. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  86202. }
  86203. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  86204. get: function () {
  86205. return this._isEnabled;
  86206. },
  86207. set: function (value) {
  86208. this._isEnabled = value;
  86209. },
  86210. enumerable: true,
  86211. configurable: true
  86212. });
  86213. LensFlareSystem.prototype.getScene = function () {
  86214. return this._scene;
  86215. };
  86216. LensFlareSystem.prototype.getEmitter = function () {
  86217. return this._emitter;
  86218. };
  86219. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  86220. this._emitter = newEmitter;
  86221. };
  86222. LensFlareSystem.prototype.getEmitterPosition = function () {
  86223. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  86224. };
  86225. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  86226. var position = this.getEmitterPosition();
  86227. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  86228. this._positionX = position.x;
  86229. this._positionY = position.y;
  86230. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  86231. if (this.viewportBorder > 0) {
  86232. globalViewport.x -= this.viewportBorder;
  86233. globalViewport.y -= this.viewportBorder;
  86234. globalViewport.width += this.viewportBorder * 2;
  86235. globalViewport.height += this.viewportBorder * 2;
  86236. position.x += this.viewportBorder;
  86237. position.y += this.viewportBorder;
  86238. this._positionX += this.viewportBorder;
  86239. this._positionY += this.viewportBorder;
  86240. }
  86241. if (position.z > 0) {
  86242. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  86243. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86244. return true;
  86245. }
  86246. return true;
  86247. }
  86248. return false;
  86249. };
  86250. /** @hidden */
  86251. LensFlareSystem.prototype._isVisible = function () {
  86252. if (!this._isEnabled || !this._scene.activeCamera) {
  86253. return false;
  86254. }
  86255. var emitterPosition = this.getEmitterPosition();
  86256. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86257. var distance = direction.length();
  86258. direction.normalize();
  86259. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86260. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86261. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86262. };
  86263. LensFlareSystem.prototype.render = function () {
  86264. if (!this._effect.isReady() || !this._scene.activeCamera)
  86265. return false;
  86266. var engine = this._scene.getEngine();
  86267. var viewport = this._scene.activeCamera.viewport;
  86268. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86269. // Position
  86270. if (!this.computeEffectivePosition(globalViewport)) {
  86271. return false;
  86272. }
  86273. // Visibility
  86274. if (!this._isVisible()) {
  86275. return false;
  86276. }
  86277. // Intensity
  86278. var awayX;
  86279. var awayY;
  86280. if (this._positionX < this.borderLimit + globalViewport.x) {
  86281. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86282. }
  86283. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86284. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86285. }
  86286. else {
  86287. awayX = 0;
  86288. }
  86289. if (this._positionY < this.borderLimit + globalViewport.y) {
  86290. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86291. }
  86292. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86293. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86294. }
  86295. else {
  86296. awayY = 0;
  86297. }
  86298. var away = (awayX > awayY) ? awayX : awayY;
  86299. away -= this.viewportBorder;
  86300. if (away > this.borderLimit) {
  86301. away = this.borderLimit;
  86302. }
  86303. var intensity = 1.0 - (away / this.borderLimit);
  86304. if (intensity < 0) {
  86305. return false;
  86306. }
  86307. if (intensity > 1.0) {
  86308. intensity = 1.0;
  86309. }
  86310. if (this.viewportBorder > 0) {
  86311. globalViewport.x += this.viewportBorder;
  86312. globalViewport.y += this.viewportBorder;
  86313. globalViewport.width -= this.viewportBorder * 2;
  86314. globalViewport.height -= this.viewportBorder * 2;
  86315. this._positionX -= this.viewportBorder;
  86316. this._positionY -= this.viewportBorder;
  86317. }
  86318. // Position
  86319. var centerX = globalViewport.x + globalViewport.width / 2;
  86320. var centerY = globalViewport.y + globalViewport.height / 2;
  86321. var distX = centerX - this._positionX;
  86322. var distY = centerY - this._positionY;
  86323. // Effects
  86324. engine.enableEffect(this._effect);
  86325. engine.setState(false);
  86326. engine.setDepthBuffer(false);
  86327. // VBOs
  86328. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86329. // Flares
  86330. for (var index = 0; index < this.lensFlares.length; index++) {
  86331. var flare = this.lensFlares[index];
  86332. engine.setAlphaMode(flare.alphaMode);
  86333. var x = centerX - (distX * flare.position);
  86334. var y = centerY - (distY * flare.position);
  86335. var cw = flare.size;
  86336. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86337. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86338. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86339. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86340. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86341. // Texture
  86342. this._effect.setTexture("textureSampler", flare.texture);
  86343. // Color
  86344. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86345. // Draw order
  86346. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86347. }
  86348. engine.setDepthBuffer(true);
  86349. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86350. return true;
  86351. };
  86352. LensFlareSystem.prototype.dispose = function () {
  86353. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86354. if (vertexBuffer) {
  86355. vertexBuffer.dispose();
  86356. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86357. }
  86358. if (this._indexBuffer) {
  86359. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86360. this._indexBuffer = null;
  86361. }
  86362. while (this.lensFlares.length) {
  86363. this.lensFlares[0].dispose();
  86364. }
  86365. // Remove from scene
  86366. var index = this._scene.lensFlareSystems.indexOf(this);
  86367. this._scene.lensFlareSystems.splice(index, 1);
  86368. };
  86369. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86370. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86371. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86372. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86373. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86374. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86375. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86376. var parsedFlare = parsedLensFlareSystem.flares[index];
  86377. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86378. }
  86379. return lensFlareSystem;
  86380. };
  86381. LensFlareSystem.prototype.serialize = function () {
  86382. var serializationObject = {};
  86383. serializationObject.id = this.id;
  86384. serializationObject.name = this.name;
  86385. serializationObject.emitterId = this.getEmitter().id;
  86386. serializationObject.borderLimit = this.borderLimit;
  86387. serializationObject.flares = [];
  86388. for (var index = 0; index < this.lensFlares.length; index++) {
  86389. var flare = this.lensFlares[index];
  86390. serializationObject.flares.push({
  86391. size: flare.size,
  86392. position: flare.position,
  86393. color: flare.color.asArray(),
  86394. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86395. });
  86396. }
  86397. return serializationObject;
  86398. };
  86399. return LensFlareSystem;
  86400. }());
  86401. BABYLON.LensFlareSystem = LensFlareSystem;
  86402. })(BABYLON || (BABYLON = {}));
  86403. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86404. var BABYLON;
  86405. (function (BABYLON) {
  86406. /**
  86407. * This is a holder class for the physics joint created by the physics plugin.
  86408. * It holds a set of functions to control the underlying joint.
  86409. */
  86410. var PhysicsJoint = /** @class */ (function () {
  86411. function PhysicsJoint(type, jointData) {
  86412. this.type = type;
  86413. this.jointData = jointData;
  86414. jointData.nativeParams = jointData.nativeParams || {};
  86415. }
  86416. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86417. get: function () {
  86418. return this._physicsJoint;
  86419. },
  86420. set: function (newJoint) {
  86421. if (this._physicsJoint) {
  86422. //remove from the wolrd
  86423. }
  86424. this._physicsJoint = newJoint;
  86425. },
  86426. enumerable: true,
  86427. configurable: true
  86428. });
  86429. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86430. set: function (physicsPlugin) {
  86431. this._physicsPlugin = physicsPlugin;
  86432. },
  86433. enumerable: true,
  86434. configurable: true
  86435. });
  86436. /**
  86437. * Execute a function that is physics-plugin specific.
  86438. * @param {Function} func the function that will be executed.
  86439. * It accepts two parameters: the physics world and the physics joint.
  86440. */
  86441. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86442. func(this._physicsPlugin.world, this._physicsJoint);
  86443. };
  86444. //TODO check if the native joints are the same
  86445. //Joint Types
  86446. PhysicsJoint.DistanceJoint = 0;
  86447. PhysicsJoint.HingeJoint = 1;
  86448. PhysicsJoint.BallAndSocketJoint = 2;
  86449. PhysicsJoint.WheelJoint = 3;
  86450. PhysicsJoint.SliderJoint = 4;
  86451. //OIMO
  86452. PhysicsJoint.PrismaticJoint = 5;
  86453. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86454. PhysicsJoint.UniversalJoint = 6;
  86455. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86456. //Cannon
  86457. //Similar to a Ball-Joint. Different in params
  86458. PhysicsJoint.PointToPointJoint = 8;
  86459. //Cannon only at the moment
  86460. PhysicsJoint.SpringJoint = 9;
  86461. PhysicsJoint.LockJoint = 10;
  86462. return PhysicsJoint;
  86463. }());
  86464. BABYLON.PhysicsJoint = PhysicsJoint;
  86465. /**
  86466. * A class representing a physics distance joint.
  86467. */
  86468. var DistanceJoint = /** @class */ (function (_super) {
  86469. __extends(DistanceJoint, _super);
  86470. function DistanceJoint(jointData) {
  86471. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86472. }
  86473. /**
  86474. * Update the predefined distance.
  86475. */
  86476. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86477. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86478. };
  86479. return DistanceJoint;
  86480. }(PhysicsJoint));
  86481. BABYLON.DistanceJoint = DistanceJoint;
  86482. var MotorEnabledJoint = /** @class */ (function (_super) {
  86483. __extends(MotorEnabledJoint, _super);
  86484. function MotorEnabledJoint(type, jointData) {
  86485. return _super.call(this, type, jointData) || this;
  86486. }
  86487. /**
  86488. * Set the motor values.
  86489. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86490. * @param {number} force the force to apply
  86491. * @param {number} maxForce max force for this motor.
  86492. */
  86493. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86494. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86495. };
  86496. /**
  86497. * Set the motor's limits.
  86498. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86499. */
  86500. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86501. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86502. };
  86503. return MotorEnabledJoint;
  86504. }(PhysicsJoint));
  86505. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86506. /**
  86507. * This class represents a single hinge physics joint
  86508. */
  86509. var HingeJoint = /** @class */ (function (_super) {
  86510. __extends(HingeJoint, _super);
  86511. function HingeJoint(jointData) {
  86512. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  86513. }
  86514. /**
  86515. * Set the motor values.
  86516. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86517. * @param {number} force the force to apply
  86518. * @param {number} maxForce max force for this motor.
  86519. */
  86520. HingeJoint.prototype.setMotor = function (force, maxForce) {
  86521. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86522. };
  86523. /**
  86524. * Set the motor's limits.
  86525. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86526. */
  86527. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86528. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86529. };
  86530. return HingeJoint;
  86531. }(MotorEnabledJoint));
  86532. BABYLON.HingeJoint = HingeJoint;
  86533. /**
  86534. * This class represents a dual hinge physics joint (same as wheel joint)
  86535. */
  86536. var Hinge2Joint = /** @class */ (function (_super) {
  86537. __extends(Hinge2Joint, _super);
  86538. function Hinge2Joint(jointData) {
  86539. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  86540. }
  86541. /**
  86542. * Set the motor values.
  86543. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86544. * @param {number} force the force to apply
  86545. * @param {number} maxForce max force for this motor.
  86546. * @param {motorIndex} the motor's index, 0 or 1.
  86547. */
  86548. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  86549. if (motorIndex === void 0) { motorIndex = 0; }
  86550. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  86551. };
  86552. /**
  86553. * Set the motor limits.
  86554. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86555. * @param {number} upperLimit the upper limit
  86556. * @param {number} lowerLimit lower limit
  86557. * @param {motorIndex} the motor's index, 0 or 1.
  86558. */
  86559. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  86560. if (motorIndex === void 0) { motorIndex = 0; }
  86561. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  86562. };
  86563. return Hinge2Joint;
  86564. }(MotorEnabledJoint));
  86565. BABYLON.Hinge2Joint = Hinge2Joint;
  86566. })(BABYLON || (BABYLON = {}));
  86567. //# sourceMappingURL=babylon.physicsJoint.js.map
  86568. var BABYLON;
  86569. (function (BABYLON) {
  86570. var PhysicsImpostor = /** @class */ (function () {
  86571. function PhysicsImpostor(object, type, _options, _scene) {
  86572. if (_options === void 0) { _options = { mass: 0 }; }
  86573. var _this = this;
  86574. this.object = object;
  86575. this.type = type;
  86576. this._options = _options;
  86577. this._scene = _scene;
  86578. this._bodyUpdateRequired = false;
  86579. this._onBeforePhysicsStepCallbacks = new Array();
  86580. this._onAfterPhysicsStepCallbacks = new Array();
  86581. this._onPhysicsCollideCallbacks = [];
  86582. this._deltaPosition = BABYLON.Vector3.Zero();
  86583. this._isDisposed = false;
  86584. //temp variables for parent rotation calculations
  86585. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  86586. this._tmpQuat = new BABYLON.Quaternion();
  86587. this._tmpQuat2 = new BABYLON.Quaternion();
  86588. /**
  86589. * this function is executed by the physics engine.
  86590. */
  86591. this.beforeStep = function () {
  86592. if (!_this._physicsEngine) {
  86593. return;
  86594. }
  86595. _this.object.translate(_this._deltaPosition, -1);
  86596. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  86597. _this.object.computeWorldMatrix(false);
  86598. if (_this.object.parent && _this.object.rotationQuaternion) {
  86599. _this.getParentsRotation();
  86600. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  86601. }
  86602. else {
  86603. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  86604. }
  86605. if (!_this._options.disableBidirectionalTransformation) {
  86606. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  86607. }
  86608. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  86609. func(_this);
  86610. });
  86611. };
  86612. /**
  86613. * this function is executed by the physics engine.
  86614. */
  86615. this.afterStep = function () {
  86616. if (!_this._physicsEngine) {
  86617. return;
  86618. }
  86619. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  86620. func(_this);
  86621. });
  86622. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  86623. // object has now its world rotation. needs to be converted to local.
  86624. if (_this.object.parent && _this.object.rotationQuaternion) {
  86625. _this.getParentsRotation();
  86626. _this._tmpQuat.conjugateInPlace();
  86627. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  86628. }
  86629. // take the position set and make it the absolute position of this object.
  86630. _this.object.setAbsolutePosition(_this.object.position);
  86631. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  86632. _this.object.translate(_this._deltaPosition, 1);
  86633. };
  86634. /**
  86635. * Legacy collision detection event support
  86636. */
  86637. this.onCollideEvent = null;
  86638. //event and body object due to cannon's event-based architecture.
  86639. this.onCollide = function (e) {
  86640. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  86641. return;
  86642. }
  86643. if (!_this._physicsEngine) {
  86644. return;
  86645. }
  86646. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  86647. if (otherImpostor) {
  86648. // Legacy collision detection event support
  86649. if (_this.onCollideEvent) {
  86650. _this.onCollideEvent(_this, otherImpostor);
  86651. }
  86652. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  86653. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  86654. }).forEach(function (obj) {
  86655. obj.callback(_this, otherImpostor);
  86656. });
  86657. }
  86658. };
  86659. //sanity check!
  86660. if (!this.object) {
  86661. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  86662. return;
  86663. }
  86664. //legacy support for old syntax.
  86665. if (!this._scene && object.getScene) {
  86666. this._scene = object.getScene();
  86667. }
  86668. if (!this._scene) {
  86669. return;
  86670. }
  86671. this._physicsEngine = this._scene.getPhysicsEngine();
  86672. if (!this._physicsEngine) {
  86673. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  86674. }
  86675. else {
  86676. //set the object's quaternion, if not set
  86677. if (!this.object.rotationQuaternion) {
  86678. if (this.object.rotation) {
  86679. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  86680. }
  86681. else {
  86682. this.object.rotationQuaternion = new BABYLON.Quaternion();
  86683. }
  86684. }
  86685. //default options params
  86686. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  86687. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  86688. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  86689. this._joints = [];
  86690. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  86691. if (!this.object.parent || this._options.ignoreParent) {
  86692. this._init();
  86693. }
  86694. else if (this.object.parent.physicsImpostor) {
  86695. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  86696. }
  86697. }
  86698. }
  86699. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  86700. get: function () {
  86701. return this._isDisposed;
  86702. },
  86703. enumerable: true,
  86704. configurable: true
  86705. });
  86706. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  86707. get: function () {
  86708. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  86709. },
  86710. set: function (value) {
  86711. this.setMass(value);
  86712. },
  86713. enumerable: true,
  86714. configurable: true
  86715. });
  86716. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  86717. get: function () {
  86718. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  86719. },
  86720. set: function (value) {
  86721. if (!this._physicsEngine) {
  86722. return;
  86723. }
  86724. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  86725. },
  86726. enumerable: true,
  86727. configurable: true
  86728. });
  86729. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  86730. get: function () {
  86731. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  86732. },
  86733. set: function (value) {
  86734. if (!this._physicsEngine) {
  86735. return;
  86736. }
  86737. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  86738. },
  86739. enumerable: true,
  86740. configurable: true
  86741. });
  86742. /**
  86743. * This function will completly initialize this impostor.
  86744. * It will create a new body - but only if this mesh has no parent.
  86745. * If it has, this impostor will not be used other than to define the impostor
  86746. * of the child mesh.
  86747. * @hidden
  86748. */
  86749. PhysicsImpostor.prototype._init = function () {
  86750. if (!this._physicsEngine) {
  86751. return;
  86752. }
  86753. this._physicsEngine.removeImpostor(this);
  86754. this.physicsBody = null;
  86755. this._parent = this._parent || this._getPhysicsParent();
  86756. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  86757. this._physicsEngine.addImpostor(this);
  86758. }
  86759. };
  86760. PhysicsImpostor.prototype._getPhysicsParent = function () {
  86761. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  86762. var parentMesh = this.object.parent;
  86763. return parentMesh.physicsImpostor;
  86764. }
  86765. return null;
  86766. };
  86767. /**
  86768. * Should a new body be generated.
  86769. */
  86770. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  86771. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  86772. };
  86773. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  86774. this.forceUpdate();
  86775. };
  86776. /**
  86777. * Force a regeneration of this or the parent's impostor's body.
  86778. * Use under cautious - This will remove all joints already implemented.
  86779. */
  86780. PhysicsImpostor.prototype.forceUpdate = function () {
  86781. this._init();
  86782. if (this.parent && !this._options.ignoreParent) {
  86783. this.parent.forceUpdate();
  86784. }
  86785. };
  86786. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  86787. /*public get mesh(): AbstractMesh {
  86788. return this._mesh;
  86789. }*/
  86790. /**
  86791. * Gets the body that holds this impostor. Either its own, or its parent.
  86792. */
  86793. get: function () {
  86794. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  86795. },
  86796. /**
  86797. * Set the physics body. Used mainly by the physics engine/plugin
  86798. */
  86799. set: function (physicsBody) {
  86800. if (this._physicsBody && this._physicsEngine) {
  86801. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  86802. }
  86803. this._physicsBody = physicsBody;
  86804. this.resetUpdateFlags();
  86805. },
  86806. enumerable: true,
  86807. configurable: true
  86808. });
  86809. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  86810. get: function () {
  86811. return !this._options.ignoreParent && this._parent ? this._parent : null;
  86812. },
  86813. set: function (value) {
  86814. this._parent = value;
  86815. },
  86816. enumerable: true,
  86817. configurable: true
  86818. });
  86819. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  86820. this._bodyUpdateRequired = false;
  86821. };
  86822. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  86823. if (this.object.getBoundingInfo) {
  86824. var q = this.object.rotationQuaternion;
  86825. //reset rotation
  86826. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  86827. //calculate the world matrix with no rotation
  86828. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  86829. var boundingInfo = this.object.getBoundingInfo();
  86830. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  86831. //bring back the rotation
  86832. this.object.rotationQuaternion = q;
  86833. //calculate the world matrix with the new rotation
  86834. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  86835. return size;
  86836. }
  86837. else {
  86838. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  86839. }
  86840. };
  86841. PhysicsImpostor.prototype.getObjectCenter = function () {
  86842. if (this.object.getBoundingInfo) {
  86843. var boundingInfo = this.object.getBoundingInfo();
  86844. return boundingInfo.boundingBox.centerWorld;
  86845. }
  86846. else {
  86847. return this.object.position;
  86848. }
  86849. };
  86850. /**
  86851. * Get a specific parametes from the options parameter.
  86852. */
  86853. PhysicsImpostor.prototype.getParam = function (paramName) {
  86854. return this._options[paramName];
  86855. };
  86856. /**
  86857. * Sets a specific parameter in the options given to the physics plugin
  86858. */
  86859. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  86860. this._options[paramName] = value;
  86861. this._bodyUpdateRequired = true;
  86862. };
  86863. /**
  86864. * Specifically change the body's mass option. Won't recreate the physics body object
  86865. */
  86866. PhysicsImpostor.prototype.setMass = function (mass) {
  86867. if (this.getParam("mass") !== mass) {
  86868. this.setParam("mass", mass);
  86869. }
  86870. if (this._physicsEngine) {
  86871. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  86872. }
  86873. };
  86874. PhysicsImpostor.prototype.getLinearVelocity = function () {
  86875. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  86876. };
  86877. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  86878. if (this._physicsEngine) {
  86879. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  86880. }
  86881. };
  86882. PhysicsImpostor.prototype.getAngularVelocity = function () {
  86883. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  86884. };
  86885. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  86886. if (this._physicsEngine) {
  86887. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  86888. }
  86889. };
  86890. /**
  86891. * Execute a function with the physics plugin native code.
  86892. * Provide a function the will have two variables - the world object and the physics body object.
  86893. */
  86894. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  86895. if (this._physicsEngine) {
  86896. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  86897. }
  86898. };
  86899. /**
  86900. * Register a function that will be executed before the physics world is stepping forward.
  86901. */
  86902. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  86903. this._onBeforePhysicsStepCallbacks.push(func);
  86904. };
  86905. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  86906. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  86907. if (index > -1) {
  86908. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  86909. }
  86910. else {
  86911. BABYLON.Tools.Warn("Function to remove was not found");
  86912. }
  86913. };
  86914. /**
  86915. * Register a function that will be executed after the physics step
  86916. */
  86917. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  86918. this._onAfterPhysicsStepCallbacks.push(func);
  86919. };
  86920. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  86921. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  86922. if (index > -1) {
  86923. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  86924. }
  86925. else {
  86926. BABYLON.Tools.Warn("Function to remove was not found");
  86927. }
  86928. };
  86929. /**
  86930. * register a function that will be executed when this impostor collides against a different body.
  86931. */
  86932. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  86933. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86934. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  86935. };
  86936. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  86937. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86938. var index = -1;
  86939. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  86940. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  86941. // chcek the arrays match
  86942. var sameList = cbDef.otherImpostors.every(function (impostor) {
  86943. return collidedAgainstList.indexOf(impostor) > -1;
  86944. });
  86945. if (sameList) {
  86946. index = idx;
  86947. }
  86948. return sameList;
  86949. }
  86950. return false;
  86951. });
  86952. if (found) {
  86953. this._onPhysicsCollideCallbacks.splice(index, 1);
  86954. }
  86955. else {
  86956. BABYLON.Tools.Warn("Function to remove was not found");
  86957. }
  86958. };
  86959. PhysicsImpostor.prototype.getParentsRotation = function () {
  86960. var parent = this.object.parent;
  86961. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  86962. while (parent) {
  86963. if (parent.rotationQuaternion) {
  86964. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  86965. }
  86966. else {
  86967. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  86968. }
  86969. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  86970. parent = parent.parent;
  86971. }
  86972. return this._tmpQuat;
  86973. };
  86974. /**
  86975. * Apply a force
  86976. */
  86977. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  86978. if (this._physicsEngine) {
  86979. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  86980. }
  86981. return this;
  86982. };
  86983. /**
  86984. * Apply an impulse
  86985. */
  86986. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  86987. if (this._physicsEngine) {
  86988. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  86989. }
  86990. return this;
  86991. };
  86992. /**
  86993. * A help function to create a joint.
  86994. */
  86995. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  86996. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  86997. this.addJoint(otherImpostor, joint);
  86998. return this;
  86999. };
  87000. /**
  87001. * Add a joint to this impostor with a different impostor.
  87002. */
  87003. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87004. this._joints.push({
  87005. otherImpostor: otherImpostor,
  87006. joint: joint
  87007. });
  87008. if (this._physicsEngine) {
  87009. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87010. }
  87011. return this;
  87012. };
  87013. /**
  87014. * Will keep this body still, in a sleep mode.
  87015. */
  87016. PhysicsImpostor.prototype.sleep = function () {
  87017. if (this._physicsEngine) {
  87018. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87019. }
  87020. return this;
  87021. };
  87022. /**
  87023. * Wake the body up.
  87024. */
  87025. PhysicsImpostor.prototype.wakeUp = function () {
  87026. if (this._physicsEngine) {
  87027. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87028. }
  87029. return this;
  87030. };
  87031. PhysicsImpostor.prototype.clone = function (newObject) {
  87032. if (!newObject)
  87033. return null;
  87034. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87035. };
  87036. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87037. var _this = this;
  87038. //no dispose if no physics engine is available.
  87039. if (!this._physicsEngine) {
  87040. return;
  87041. }
  87042. this._joints.forEach(function (j) {
  87043. if (_this._physicsEngine) {
  87044. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87045. }
  87046. });
  87047. //dispose the physics body
  87048. this._physicsEngine.removeImpostor(this);
  87049. if (this.parent) {
  87050. this.parent.forceUpdate();
  87051. }
  87052. else {
  87053. /*this._object.getChildMeshes().forEach(function(mesh) {
  87054. if (mesh.physicsImpostor) {
  87055. if (disposeChildren) {
  87056. mesh.physicsImpostor.dispose();
  87057. mesh.physicsImpostor = null;
  87058. }
  87059. }
  87060. })*/
  87061. }
  87062. this._isDisposed = true;
  87063. };
  87064. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87065. this._deltaPosition.copyFrom(position);
  87066. };
  87067. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87068. if (!this._deltaRotation) {
  87069. this._deltaRotation = new BABYLON.Quaternion();
  87070. }
  87071. this._deltaRotation.copyFrom(rotation);
  87072. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87073. };
  87074. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87075. if (this._physicsEngine) {
  87076. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87077. }
  87078. return this;
  87079. };
  87080. PhysicsImpostor.prototype.getRadius = function () {
  87081. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87082. };
  87083. /**
  87084. * Sync a bone with this impostor
  87085. * @param bone The bone to sync to the impostor.
  87086. * @param boneMesh The mesh that the bone is influencing.
  87087. * @param jointPivot The pivot of the joint / bone in local space.
  87088. * @param distToJoint Optional distance from the impostor to the joint.
  87089. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87090. */
  87091. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  87092. var tempVec = PhysicsImpostor._tmpVecs[0];
  87093. var mesh = this.object;
  87094. if (mesh.rotationQuaternion) {
  87095. if (adjustRotation) {
  87096. var tempQuat = PhysicsImpostor._tmpQuat;
  87097. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  87098. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  87099. }
  87100. else {
  87101. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  87102. }
  87103. }
  87104. tempVec.x = 0;
  87105. tempVec.y = 0;
  87106. tempVec.z = 0;
  87107. if (jointPivot) {
  87108. tempVec.x = jointPivot.x;
  87109. tempVec.y = jointPivot.y;
  87110. tempVec.z = jointPivot.z;
  87111. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  87112. if (distToJoint === undefined || distToJoint === null) {
  87113. distToJoint = jointPivot.length();
  87114. }
  87115. tempVec.x *= distToJoint;
  87116. tempVec.y *= distToJoint;
  87117. tempVec.z *= distToJoint;
  87118. }
  87119. if (bone.getParent()) {
  87120. tempVec.addInPlace(mesh.getAbsolutePosition());
  87121. bone.setAbsolutePosition(tempVec, boneMesh);
  87122. }
  87123. else {
  87124. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  87125. boneMesh.position.x -= tempVec.x;
  87126. boneMesh.position.y -= tempVec.y;
  87127. boneMesh.position.z -= tempVec.z;
  87128. }
  87129. };
  87130. /**
  87131. * Sync impostor to a bone
  87132. * @param bone The bone that the impostor will be synced to.
  87133. * @param boneMesh The mesh that the bone is influencing.
  87134. * @param jointPivot The pivot of the joint / bone in local space.
  87135. * @param distToJoint Optional distance from the impostor to the joint.
  87136. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87137. * @param boneAxis Optional vector3 axis the bone is aligned with
  87138. */
  87139. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  87140. var mesh = this.object;
  87141. if (mesh.rotationQuaternion) {
  87142. if (adjustRotation) {
  87143. var tempQuat = PhysicsImpostor._tmpQuat;
  87144. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  87145. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  87146. }
  87147. else {
  87148. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  87149. }
  87150. }
  87151. var pos = PhysicsImpostor._tmpVecs[0];
  87152. var boneDir = PhysicsImpostor._tmpVecs[1];
  87153. if (!boneAxis) {
  87154. boneAxis = PhysicsImpostor._tmpVecs[2];
  87155. boneAxis.x = 0;
  87156. boneAxis.y = 1;
  87157. boneAxis.z = 0;
  87158. }
  87159. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  87160. bone.getAbsolutePositionToRef(boneMesh, pos);
  87161. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  87162. distToJoint = jointPivot.length();
  87163. }
  87164. if (distToJoint !== undefined && distToJoint !== null) {
  87165. pos.x += boneDir.x * distToJoint;
  87166. pos.y += boneDir.y * distToJoint;
  87167. pos.z += boneDir.z * distToJoint;
  87168. }
  87169. mesh.setAbsolutePosition(pos);
  87170. };
  87171. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  87172. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  87173. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87174. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  87175. //Impostor types
  87176. PhysicsImpostor.NoImpostor = 0;
  87177. PhysicsImpostor.SphereImpostor = 1;
  87178. PhysicsImpostor.BoxImpostor = 2;
  87179. PhysicsImpostor.PlaneImpostor = 3;
  87180. PhysicsImpostor.MeshImpostor = 4;
  87181. PhysicsImpostor.CylinderImpostor = 7;
  87182. PhysicsImpostor.ParticleImpostor = 8;
  87183. PhysicsImpostor.HeightmapImpostor = 9;
  87184. return PhysicsImpostor;
  87185. }());
  87186. BABYLON.PhysicsImpostor = PhysicsImpostor;
  87187. })(BABYLON || (BABYLON = {}));
  87188. //# sourceMappingURL=babylon.physicsImpostor.js.map
  87189. var BABYLON;
  87190. (function (BABYLON) {
  87191. var PhysicsEngine = /** @class */ (function () {
  87192. function PhysicsEngine(gravity, _physicsPlugin) {
  87193. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  87194. this._physicsPlugin = _physicsPlugin;
  87195. //new methods and parameters
  87196. this._impostors = [];
  87197. this._joints = [];
  87198. if (!this._physicsPlugin.isSupported()) {
  87199. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  87200. + "Please make sure it is included.");
  87201. }
  87202. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  87203. this.setGravity(gravity);
  87204. this.setTimeStep();
  87205. }
  87206. PhysicsEngine.prototype.setGravity = function (gravity) {
  87207. this.gravity = gravity;
  87208. this._physicsPlugin.setGravity(this.gravity);
  87209. };
  87210. /**
  87211. * Set the time step of the physics engine.
  87212. * default is 1/60.
  87213. * To slow it down, enter 1/600 for example.
  87214. * To speed it up, 1/30
  87215. * @param {number} newTimeStep the new timestep to apply to this world.
  87216. */
  87217. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  87218. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  87219. this._physicsPlugin.setTimeStep(newTimeStep);
  87220. };
  87221. /**
  87222. * Get the time step of the physics engine.
  87223. */
  87224. PhysicsEngine.prototype.getTimeStep = function () {
  87225. return this._physicsPlugin.getTimeStep();
  87226. };
  87227. PhysicsEngine.prototype.dispose = function () {
  87228. this._impostors.forEach(function (impostor) {
  87229. impostor.dispose();
  87230. });
  87231. this._physicsPlugin.dispose();
  87232. };
  87233. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  87234. return this._physicsPlugin.name;
  87235. };
  87236. /**
  87237. * Adding a new impostor for the impostor tracking.
  87238. * This will be done by the impostor itself.
  87239. * @param {PhysicsImpostor} impostor the impostor to add
  87240. */
  87241. PhysicsEngine.prototype.addImpostor = function (impostor) {
  87242. impostor.uniqueId = this._impostors.push(impostor);
  87243. //if no parent, generate the body
  87244. if (!impostor.parent) {
  87245. this._physicsPlugin.generatePhysicsBody(impostor);
  87246. }
  87247. };
  87248. /**
  87249. * Remove an impostor from the engine.
  87250. * This impostor and its mesh will not longer be updated by the physics engine.
  87251. * @param {PhysicsImpostor} impostor the impostor to remove
  87252. */
  87253. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87254. var index = this._impostors.indexOf(impostor);
  87255. if (index > -1) {
  87256. var removed = this._impostors.splice(index, 1);
  87257. //Is it needed?
  87258. if (removed.length) {
  87259. //this will also remove it from the world.
  87260. removed[0].physicsBody = null;
  87261. }
  87262. }
  87263. };
  87264. /**
  87265. * Add a joint to the physics engine
  87266. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87267. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87268. * @param {PhysicsJoint} the joint that will connect both impostors.
  87269. */
  87270. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87271. var impostorJoint = {
  87272. mainImpostor: mainImpostor,
  87273. connectedImpostor: connectedImpostor,
  87274. joint: joint
  87275. };
  87276. joint.physicsPlugin = this._physicsPlugin;
  87277. this._joints.push(impostorJoint);
  87278. this._physicsPlugin.generateJoint(impostorJoint);
  87279. };
  87280. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87281. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87282. return (impostorJoint.connectedImpostor === connectedImpostor
  87283. && impostorJoint.joint === joint
  87284. && impostorJoint.mainImpostor === mainImpostor);
  87285. });
  87286. if (matchingJoints.length) {
  87287. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87288. //TODO remove it from the list as well
  87289. }
  87290. };
  87291. /**
  87292. * Called by the scene. no need to call it.
  87293. * @hidden
  87294. */
  87295. PhysicsEngine.prototype._step = function (delta) {
  87296. var _this = this;
  87297. //check if any mesh has no body / requires an update
  87298. this._impostors.forEach(function (impostor) {
  87299. if (impostor.isBodyInitRequired()) {
  87300. _this._physicsPlugin.generatePhysicsBody(impostor);
  87301. }
  87302. });
  87303. if (delta > 0.1) {
  87304. delta = 0.1;
  87305. }
  87306. else if (delta <= 0) {
  87307. delta = 1.0 / 60.0;
  87308. }
  87309. this._physicsPlugin.executeStep(delta, this._impostors);
  87310. };
  87311. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87312. return this._physicsPlugin;
  87313. };
  87314. PhysicsEngine.prototype.getImpostors = function () {
  87315. return this._impostors;
  87316. };
  87317. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87318. for (var i = 0; i < this._impostors.length; ++i) {
  87319. if (this._impostors[i].object === object) {
  87320. return this._impostors[i];
  87321. }
  87322. }
  87323. return null;
  87324. };
  87325. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87326. for (var i = 0; i < this._impostors.length; ++i) {
  87327. if (this._impostors[i].physicsBody === body) {
  87328. return this._impostors[i];
  87329. }
  87330. }
  87331. return null;
  87332. };
  87333. // Statics
  87334. PhysicsEngine.Epsilon = 0.001;
  87335. return PhysicsEngine;
  87336. }());
  87337. BABYLON.PhysicsEngine = PhysicsEngine;
  87338. })(BABYLON || (BABYLON = {}));
  87339. //# sourceMappingURL=babylon.physicsEngine.js.map
  87340. var BABYLON;
  87341. (function (BABYLON) {
  87342. var PhysicsHelper = /** @class */ (function () {
  87343. function PhysicsHelper(scene) {
  87344. this._scene = scene;
  87345. this._physicsEngine = this._scene.getPhysicsEngine();
  87346. if (!this._physicsEngine) {
  87347. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87348. }
  87349. }
  87350. /**
  87351. * @param {Vector3} origin the origin of the explosion
  87352. * @param {number} radius the explosion radius
  87353. * @param {number} strength the explosion strength
  87354. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87355. */
  87356. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87357. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87358. if (!this._physicsEngine) {
  87359. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87360. return null;
  87361. }
  87362. var impostors = this._physicsEngine.getImpostors();
  87363. if (impostors.length === 0) {
  87364. return null;
  87365. }
  87366. var event = new PhysicsRadialExplosionEvent(this._scene);
  87367. impostors.forEach(function (impostor) {
  87368. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87369. if (!impostorForceAndContactPoint) {
  87370. return;
  87371. }
  87372. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87373. });
  87374. event.dispose(false);
  87375. return event;
  87376. };
  87377. /**
  87378. * @param {Vector3} origin the origin of the explosion
  87379. * @param {number} radius the explosion radius
  87380. * @param {number} strength the explosion strength
  87381. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87382. */
  87383. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87384. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87385. if (!this._physicsEngine) {
  87386. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87387. return null;
  87388. }
  87389. var impostors = this._physicsEngine.getImpostors();
  87390. if (impostors.length === 0) {
  87391. return null;
  87392. }
  87393. var event = new PhysicsRadialExplosionEvent(this._scene);
  87394. impostors.forEach(function (impostor) {
  87395. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87396. if (!impostorForceAndContactPoint) {
  87397. return;
  87398. }
  87399. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87400. });
  87401. event.dispose(false);
  87402. return event;
  87403. };
  87404. /**
  87405. * @param {Vector3} origin the origin of the explosion
  87406. * @param {number} radius the explosion radius
  87407. * @param {number} strength the explosion strength
  87408. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87409. */
  87410. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87411. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87412. if (!this._physicsEngine) {
  87413. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87414. return null;
  87415. }
  87416. var impostors = this._physicsEngine.getImpostors();
  87417. if (impostors.length === 0) {
  87418. return null;
  87419. }
  87420. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87421. event.dispose(false);
  87422. return event;
  87423. };
  87424. /**
  87425. * @param {Vector3} origin the origin of the updraft
  87426. * @param {number} radius the radius of the updraft
  87427. * @param {number} strength the strength of the updraft
  87428. * @param {number} height the height of the updraft
  87429. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87430. */
  87431. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87432. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87433. if (!this._physicsEngine) {
  87434. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87435. return null;
  87436. }
  87437. if (this._physicsEngine.getImpostors().length === 0) {
  87438. return null;
  87439. }
  87440. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87441. event.dispose(false);
  87442. return event;
  87443. };
  87444. /**
  87445. * @param {Vector3} origin the of the vortex
  87446. * @param {number} radius the radius of the vortex
  87447. * @param {number} strength the strength of the vortex
  87448. * @param {number} height the height of the vortex
  87449. */
  87450. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87451. if (!this._physicsEngine) {
  87452. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87453. return null;
  87454. }
  87455. if (this._physicsEngine.getImpostors().length === 0) {
  87456. return null;
  87457. }
  87458. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87459. event.dispose(false);
  87460. return event;
  87461. };
  87462. return PhysicsHelper;
  87463. }());
  87464. BABYLON.PhysicsHelper = PhysicsHelper;
  87465. /***** Radial explosion *****/
  87466. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87467. function PhysicsRadialExplosionEvent(scene) {
  87468. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87469. this._rays = [];
  87470. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87471. this._scene = scene;
  87472. }
  87473. /**
  87474. * Returns the data related to the radial explosion event (sphere & rays).
  87475. * @returns {PhysicsRadialExplosionEventData}
  87476. */
  87477. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87478. this._dataFetched = true;
  87479. return {
  87480. sphere: this._sphere,
  87481. rays: this._rays,
  87482. };
  87483. };
  87484. /**
  87485. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87486. * @param impostor
  87487. * @param {Vector3} origin the origin of the explosion
  87488. * @param {number} radius the explosion radius
  87489. * @param {number} strength the explosion strength
  87490. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87491. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87492. */
  87493. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87494. if (impostor.mass === 0) {
  87495. return null;
  87496. }
  87497. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87498. return null;
  87499. }
  87500. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87501. return null;
  87502. }
  87503. var impostorObjectCenter = impostor.getObjectCenter();
  87504. var direction = impostorObjectCenter.subtract(origin);
  87505. var ray = new BABYLON.Ray(origin, direction, radius);
  87506. this._rays.push(ray);
  87507. var hit = ray.intersectsMesh(impostor.object);
  87508. var contactPoint = hit.pickedPoint;
  87509. if (!contactPoint) {
  87510. return null;
  87511. }
  87512. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  87513. if (distanceFromOrigin > radius) {
  87514. return null;
  87515. }
  87516. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  87517. ? strength
  87518. : strength * (1 - (distanceFromOrigin / radius));
  87519. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87520. return { force: force, contactPoint: contactPoint };
  87521. };
  87522. /**
  87523. * Disposes the sphere.
  87524. * @param {bolean} force
  87525. */
  87526. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  87527. var _this = this;
  87528. if (force === void 0) { force = true; }
  87529. if (force) {
  87530. this._sphere.dispose();
  87531. }
  87532. else {
  87533. setTimeout(function () {
  87534. if (!_this._dataFetched) {
  87535. _this._sphere.dispose();
  87536. }
  87537. }, 0);
  87538. }
  87539. };
  87540. /*** Helpers ***/
  87541. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  87542. if (!this._sphere) {
  87543. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  87544. this._sphere.isVisible = false;
  87545. }
  87546. };
  87547. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  87548. var impostorObject = impostor.object;
  87549. this._prepareSphere();
  87550. this._sphere.position = origin;
  87551. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  87552. this._sphere._updateBoundingInfo();
  87553. this._sphere.computeWorldMatrix(true);
  87554. return this._sphere.intersectsMesh(impostorObject, true);
  87555. };
  87556. return PhysicsRadialExplosionEvent;
  87557. }());
  87558. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  87559. /***** Gravitational Field *****/
  87560. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  87561. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  87562. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87563. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87564. this._physicsHelper = physicsHelper;
  87565. this._scene = scene;
  87566. this._origin = origin;
  87567. this._radius = radius;
  87568. this._strength = strength;
  87569. this._falloff = falloff;
  87570. this._tickCallback = this._tick.bind(this);
  87571. }
  87572. /**
  87573. * Returns the data related to the gravitational field event (sphere).
  87574. * @returns {PhysicsGravitationalFieldEventData}
  87575. */
  87576. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  87577. this._dataFetched = true;
  87578. return {
  87579. sphere: this._sphere,
  87580. };
  87581. };
  87582. /**
  87583. * Enables the gravitational field.
  87584. */
  87585. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  87586. this._tickCallback.call(this);
  87587. this._scene.registerBeforeRender(this._tickCallback);
  87588. };
  87589. /**
  87590. * Disables the gravitational field.
  87591. */
  87592. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  87593. this._scene.unregisterBeforeRender(this._tickCallback);
  87594. };
  87595. /**
  87596. * Disposes the sphere.
  87597. * @param {bolean} force
  87598. */
  87599. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  87600. var _this = this;
  87601. if (force === void 0) { force = true; }
  87602. if (force) {
  87603. this._sphere.dispose();
  87604. }
  87605. else {
  87606. setTimeout(function () {
  87607. if (!_this._dataFetched) {
  87608. _this._sphere.dispose();
  87609. }
  87610. }, 0);
  87611. }
  87612. };
  87613. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  87614. // Since the params won't change, we fetch the event only once
  87615. if (this._sphere) {
  87616. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87617. }
  87618. else {
  87619. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87620. if (radialExplosionEvent) {
  87621. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  87622. }
  87623. }
  87624. };
  87625. return PhysicsGravitationalFieldEvent;
  87626. }());
  87627. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  87628. /***** Updraft *****/
  87629. var PhysicsUpdraftEvent = /** @class */ (function () {
  87630. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  87631. this._scene = _scene;
  87632. this._origin = _origin;
  87633. this._radius = _radius;
  87634. this._strength = _strength;
  87635. this._height = _height;
  87636. this._updraftMode = _updraftMode;
  87637. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87638. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  87639. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87640. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87641. this._physicsEngine = this._scene.getPhysicsEngine();
  87642. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87643. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87644. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87645. this._originDirection = this._origin.subtract(this._originTop).normalize();
  87646. }
  87647. this._tickCallback = this._tick.bind(this);
  87648. }
  87649. /**
  87650. * Returns the data related to the updraft event (cylinder).
  87651. * @returns {PhysicsUpdraftEventData}
  87652. */
  87653. PhysicsUpdraftEvent.prototype.getData = function () {
  87654. this._dataFetched = true;
  87655. return {
  87656. cylinder: this._cylinder,
  87657. };
  87658. };
  87659. /**
  87660. * Enables the updraft.
  87661. */
  87662. PhysicsUpdraftEvent.prototype.enable = function () {
  87663. this._tickCallback.call(this);
  87664. this._scene.registerBeforeRender(this._tickCallback);
  87665. };
  87666. /**
  87667. * Disables the cortex.
  87668. */
  87669. PhysicsUpdraftEvent.prototype.disable = function () {
  87670. this._scene.unregisterBeforeRender(this._tickCallback);
  87671. };
  87672. /**
  87673. * Disposes the sphere.
  87674. * @param {bolean} force
  87675. */
  87676. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  87677. var _this = this;
  87678. if (force === void 0) { force = true; }
  87679. if (force) {
  87680. this._cylinder.dispose();
  87681. }
  87682. else {
  87683. setTimeout(function () {
  87684. if (!_this._dataFetched) {
  87685. _this._cylinder.dispose();
  87686. }
  87687. }, 0);
  87688. }
  87689. };
  87690. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87691. if (impostor.mass === 0) {
  87692. return null;
  87693. }
  87694. if (!this._intersectsWithCylinder(impostor)) {
  87695. return null;
  87696. }
  87697. var impostorObjectCenter = impostor.getObjectCenter();
  87698. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87699. var direction = this._originDirection;
  87700. }
  87701. else {
  87702. var direction = impostorObjectCenter.subtract(this._originTop);
  87703. }
  87704. var multiplier = this._strength * -1;
  87705. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87706. return { force: force, contactPoint: impostorObjectCenter };
  87707. };
  87708. PhysicsUpdraftEvent.prototype._tick = function () {
  87709. var _this = this;
  87710. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87711. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87712. if (!impostorForceAndContactPoint) {
  87713. return;
  87714. }
  87715. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87716. });
  87717. };
  87718. /*** Helpers ***/
  87719. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  87720. if (!this._cylinder) {
  87721. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  87722. height: this._height,
  87723. diameter: this._radius * 2,
  87724. }, this._scene);
  87725. this._cylinder.isVisible = false;
  87726. }
  87727. };
  87728. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  87729. var impostorObject = impostor.object;
  87730. this._prepareCylinder();
  87731. this._cylinder.position = this._cylinderPosition;
  87732. return this._cylinder.intersectsMesh(impostorObject, true);
  87733. };
  87734. return PhysicsUpdraftEvent;
  87735. }());
  87736. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  87737. /***** Vortex *****/
  87738. var PhysicsVortexEvent = /** @class */ (function () {
  87739. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  87740. this._scene = _scene;
  87741. this._origin = _origin;
  87742. this._radius = _radius;
  87743. this._strength = _strength;
  87744. this._height = _height;
  87745. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87746. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  87747. this._updraftMultiplier = 0.02;
  87748. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87749. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87750. this._physicsEngine = this._scene.getPhysicsEngine();
  87751. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87752. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87753. this._tickCallback = this._tick.bind(this);
  87754. }
  87755. /**
  87756. * Returns the data related to the vortex event (cylinder).
  87757. * @returns {PhysicsVortexEventData}
  87758. */
  87759. PhysicsVortexEvent.prototype.getData = function () {
  87760. this._dataFetched = true;
  87761. return {
  87762. cylinder: this._cylinder,
  87763. };
  87764. };
  87765. /**
  87766. * Enables the vortex.
  87767. */
  87768. PhysicsVortexEvent.prototype.enable = function () {
  87769. this._tickCallback.call(this);
  87770. this._scene.registerBeforeRender(this._tickCallback);
  87771. };
  87772. /**
  87773. * Disables the cortex.
  87774. */
  87775. PhysicsVortexEvent.prototype.disable = function () {
  87776. this._scene.unregisterBeforeRender(this._tickCallback);
  87777. };
  87778. /**
  87779. * Disposes the sphere.
  87780. * @param {bolean} force
  87781. */
  87782. PhysicsVortexEvent.prototype.dispose = function (force) {
  87783. var _this = this;
  87784. if (force === void 0) { force = true; }
  87785. if (force) {
  87786. this._cylinder.dispose();
  87787. }
  87788. else {
  87789. setTimeout(function () {
  87790. if (!_this._dataFetched) {
  87791. _this._cylinder.dispose();
  87792. }
  87793. }, 0);
  87794. }
  87795. };
  87796. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87797. if (impostor.mass === 0) {
  87798. return null;
  87799. }
  87800. if (!this._intersectsWithCylinder(impostor)) {
  87801. return null;
  87802. }
  87803. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87804. return null;
  87805. }
  87806. var impostorObjectCenter = impostor.getObjectCenter();
  87807. 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)
  87808. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  87809. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  87810. var hit = ray.intersectsMesh(impostor.object);
  87811. var contactPoint = hit.pickedPoint;
  87812. if (!contactPoint) {
  87813. return null;
  87814. }
  87815. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  87816. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  87817. var directionToOrigin = contactPoint.normalize();
  87818. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  87819. directionToOrigin = directionToOrigin.negate();
  87820. }
  87821. // TODO: find a more physically based solution
  87822. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  87823. var forceX = directionToOrigin.x * this._strength / 8;
  87824. var forceY = directionToOrigin.y * this._updraftMultiplier;
  87825. var forceZ = directionToOrigin.z * this._strength / 8;
  87826. }
  87827. else {
  87828. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  87829. var forceY = this._originTop.y * this._updraftMultiplier;
  87830. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  87831. }
  87832. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  87833. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  87834. return { force: force, contactPoint: impostorObjectCenter };
  87835. };
  87836. PhysicsVortexEvent.prototype._tick = function () {
  87837. var _this = this;
  87838. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87839. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87840. if (!impostorForceAndContactPoint) {
  87841. return;
  87842. }
  87843. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87844. });
  87845. };
  87846. /*** Helpers ***/
  87847. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  87848. if (!this._cylinder) {
  87849. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  87850. height: this._height,
  87851. diameter: this._radius * 2,
  87852. }, this._scene);
  87853. this._cylinder.isVisible = false;
  87854. }
  87855. };
  87856. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  87857. var impostorObject = impostor.object;
  87858. this._prepareCylinder();
  87859. this._cylinder.position = this._cylinderPosition;
  87860. return this._cylinder.intersectsMesh(impostorObject, true);
  87861. };
  87862. return PhysicsVortexEvent;
  87863. }());
  87864. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  87865. /***** Enums *****/
  87866. /**
  87867. * The strenght of the force in correspondence to the distance of the affected object
  87868. */
  87869. var PhysicsRadialImpulseFalloff;
  87870. (function (PhysicsRadialImpulseFalloff) {
  87871. /** Defines that impulse is constant in strength across it's whole radius */
  87872. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  87873. /** DEfines that impulse gets weaker if it's further from the origin */
  87874. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  87875. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  87876. /**
  87877. * The strenght of the force in correspondence to the distance of the affected object
  87878. */
  87879. var PhysicsUpdraftMode;
  87880. (function (PhysicsUpdraftMode) {
  87881. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  87882. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  87883. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  87884. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  87885. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  87886. })(BABYLON || (BABYLON = {}));
  87887. //# sourceMappingURL=babylon.physicsHelper.js.map
  87888. var BABYLON;
  87889. (function (BABYLON) {
  87890. var CannonJSPlugin = /** @class */ (function () {
  87891. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  87892. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  87893. if (iterations === void 0) { iterations = 10; }
  87894. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  87895. this.name = "CannonJSPlugin";
  87896. this._physicsMaterials = new Array();
  87897. this._fixedTimeStep = 1 / 60;
  87898. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  87899. this.BJSCANNON = CANNON;
  87900. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  87901. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  87902. this._tmpPosition = BABYLON.Vector3.Zero();
  87903. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  87904. this._tmpUnityRotation = new BABYLON.Quaternion();
  87905. if (!this.isSupported()) {
  87906. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  87907. return;
  87908. }
  87909. this._extendNamespace();
  87910. this.world = new this.BJSCANNON.World();
  87911. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  87912. this.world.solver.iterations = iterations;
  87913. }
  87914. CannonJSPlugin.prototype.setGravity = function (gravity) {
  87915. this.world.gravity.copy(gravity);
  87916. };
  87917. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  87918. this._fixedTimeStep = timeStep;
  87919. };
  87920. CannonJSPlugin.prototype.getTimeStep = function () {
  87921. return this._fixedTimeStep;
  87922. };
  87923. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  87924. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  87925. };
  87926. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87927. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87928. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87929. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  87930. };
  87931. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87932. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87933. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87934. impostor.physicsBody.applyForce(impulse, worldPoint);
  87935. };
  87936. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87937. //parent-child relationship. Does this impostor has a parent impostor?
  87938. if (impostor.parent) {
  87939. if (impostor.physicsBody) {
  87940. this.removePhysicsBody(impostor);
  87941. //TODO is that needed?
  87942. impostor.forceUpdate();
  87943. }
  87944. return;
  87945. }
  87946. //should a new body be created for this impostor?
  87947. if (impostor.isBodyInitRequired()) {
  87948. var shape = this._createShape(impostor);
  87949. //unregister events, if body is being changed
  87950. var oldBody = impostor.physicsBody;
  87951. if (oldBody) {
  87952. this.removePhysicsBody(impostor);
  87953. }
  87954. //create the body and material
  87955. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  87956. var bodyCreationObject = {
  87957. mass: impostor.getParam("mass"),
  87958. material: material
  87959. };
  87960. // A simple extend, in case native options were used.
  87961. var nativeOptions = impostor.getParam("nativeOptions");
  87962. for (var key in nativeOptions) {
  87963. if (nativeOptions.hasOwnProperty(key)) {
  87964. bodyCreationObject[key] = nativeOptions[key];
  87965. }
  87966. }
  87967. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  87968. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  87969. this.world.addEventListener("preStep", impostor.beforeStep);
  87970. this.world.addEventListener("postStep", impostor.afterStep);
  87971. impostor.physicsBody.addShape(shape);
  87972. this.world.add(impostor.physicsBody);
  87973. //try to keep the body moving in the right direction by taking old properties.
  87974. //Should be tested!
  87975. if (oldBody) {
  87976. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  87977. impostor.physicsBody[param].copy(oldBody[param]);
  87978. });
  87979. }
  87980. this._processChildMeshes(impostor);
  87981. }
  87982. //now update the body's transformation
  87983. this._updatePhysicsBodyTransformation(impostor);
  87984. };
  87985. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  87986. var _this = this;
  87987. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  87988. var currentRotation = mainImpostor.object.rotationQuaternion;
  87989. if (meshChildren.length) {
  87990. var processMesh = function (localPosition, mesh) {
  87991. if (!currentRotation || !mesh.rotationQuaternion) {
  87992. return;
  87993. }
  87994. var childImpostor = mesh.getPhysicsImpostor();
  87995. if (childImpostor) {
  87996. var parent = childImpostor.parent;
  87997. if (parent !== mainImpostor) {
  87998. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  87999. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88000. if (childImpostor.physicsBody) {
  88001. _this.removePhysicsBody(childImpostor);
  88002. childImpostor.physicsBody = null;
  88003. }
  88004. childImpostor.parent = mainImpostor;
  88005. childImpostor.resetUpdateFlags();
  88006. 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));
  88007. //Add the mass of the children.
  88008. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88009. }
  88010. }
  88011. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88012. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88013. };
  88014. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88015. }
  88016. };
  88017. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88018. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88019. this.world.removeEventListener("preStep", impostor.beforeStep);
  88020. this.world.removeEventListener("postStep", impostor.afterStep);
  88021. this.world.remove(impostor.physicsBody);
  88022. };
  88023. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88024. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88025. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88026. if (!mainBody || !connectedBody) {
  88027. return;
  88028. }
  88029. var constraint;
  88030. var jointData = impostorJoint.joint.jointData;
  88031. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88032. var constraintData = {
  88033. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88034. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88035. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88036. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88037. maxForce: jointData.nativeParams.maxForce,
  88038. collideConnected: !!jointData.collision
  88039. };
  88040. switch (impostorJoint.joint.type) {
  88041. case BABYLON.PhysicsJoint.HingeJoint:
  88042. case BABYLON.PhysicsJoint.Hinge2Joint:
  88043. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88044. break;
  88045. case BABYLON.PhysicsJoint.DistanceJoint:
  88046. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88047. break;
  88048. case BABYLON.PhysicsJoint.SpringJoint:
  88049. var springData = jointData;
  88050. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88051. restLength: springData.length,
  88052. stiffness: springData.stiffness,
  88053. damping: springData.damping,
  88054. localAnchorA: constraintData.pivotA,
  88055. localAnchorB: constraintData.pivotB
  88056. });
  88057. break;
  88058. case BABYLON.PhysicsJoint.LockJoint:
  88059. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88060. break;
  88061. case BABYLON.PhysicsJoint.PointToPointJoint:
  88062. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88063. default:
  88064. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88065. break;
  88066. }
  88067. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88068. constraint.collideConnected = !!jointData.collision;
  88069. impostorJoint.joint.physicsJoint = constraint;
  88070. //don't add spring as constraint, as it is not one.
  88071. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88072. this.world.addConstraint(constraint);
  88073. }
  88074. else {
  88075. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  88076. constraint.applyForce();
  88077. });
  88078. }
  88079. };
  88080. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88081. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  88082. };
  88083. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  88084. var index;
  88085. var mat;
  88086. for (index = 0; index < this._physicsMaterials.length; index++) {
  88087. mat = this._physicsMaterials[index];
  88088. if (mat.friction === friction && mat.restitution === restitution) {
  88089. return mat;
  88090. }
  88091. }
  88092. var currentMat = new this.BJSCANNON.Material(name);
  88093. currentMat.friction = friction;
  88094. currentMat.restitution = restitution;
  88095. this._physicsMaterials.push(currentMat);
  88096. return currentMat;
  88097. };
  88098. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  88099. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  88100. };
  88101. CannonJSPlugin.prototype._createShape = function (impostor) {
  88102. var object = impostor.object;
  88103. var returnValue;
  88104. var extendSize = impostor.getObjectExtendSize();
  88105. switch (impostor.type) {
  88106. case BABYLON.PhysicsImpostor.SphereImpostor:
  88107. var radiusX = extendSize.x;
  88108. var radiusY = extendSize.y;
  88109. var radiusZ = extendSize.z;
  88110. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  88111. break;
  88112. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  88113. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88114. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  88115. break;
  88116. case BABYLON.PhysicsImpostor.BoxImpostor:
  88117. var box = extendSize.scale(0.5);
  88118. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  88119. break;
  88120. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88121. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  88122. returnValue = new this.BJSCANNON.Plane();
  88123. break;
  88124. case BABYLON.PhysicsImpostor.MeshImpostor:
  88125. // should transform the vertex data to world coordinates!!
  88126. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  88127. var rawFaces = object.getIndices ? object.getIndices() : [];
  88128. if (!rawVerts)
  88129. return;
  88130. // get only scale! so the object could transform correctly.
  88131. var oldPosition = object.position.clone();
  88132. var oldRotation = object.rotation && object.rotation.clone();
  88133. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  88134. object.position.copyFromFloats(0, 0, 0);
  88135. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88136. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88137. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88138. var transform = object.computeWorldMatrix(true);
  88139. // convert rawVerts to object space
  88140. var temp = new Array();
  88141. var index;
  88142. for (index = 0; index < rawVerts.length; index += 3) {
  88143. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  88144. }
  88145. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  88146. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  88147. //now set back the transformation!
  88148. object.position.copyFrom(oldPosition);
  88149. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  88150. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  88151. break;
  88152. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  88153. var oldPosition2 = object.position.clone();
  88154. var oldRotation2 = object.rotation && object.rotation.clone();
  88155. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  88156. object.position.copyFromFloats(0, 0, 0);
  88157. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88158. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88159. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88160. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  88161. returnValue = this._createHeightmap(object);
  88162. object.position.copyFrom(oldPosition2);
  88163. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  88164. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  88165. object.computeWorldMatrix(true);
  88166. break;
  88167. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88168. returnValue = new this.BJSCANNON.Particle();
  88169. break;
  88170. }
  88171. return returnValue;
  88172. };
  88173. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  88174. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88175. var transform = object.computeWorldMatrix(true);
  88176. // convert rawVerts to object space
  88177. var temp = new Array();
  88178. var index;
  88179. for (index = 0; index < pos.length; index += 3) {
  88180. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  88181. }
  88182. pos = temp;
  88183. var matrix = new Array();
  88184. //For now pointDepth will not be used and will be automatically calculated.
  88185. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  88186. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  88187. var boundingInfo = object.getBoundingInfo();
  88188. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  88189. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  88190. var elementSize = dim * 2 / arraySize;
  88191. for (var i = 0; i < pos.length; i = i + 3) {
  88192. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  88193. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  88194. var y = -pos[i + 2] + minY;
  88195. if (!matrix[x]) {
  88196. matrix[x] = [];
  88197. }
  88198. if (!matrix[x][z]) {
  88199. matrix[x][z] = y;
  88200. }
  88201. matrix[x][z] = Math.max(y, matrix[x][z]);
  88202. }
  88203. for (var x = 0; x <= arraySize; ++x) {
  88204. if (!matrix[x]) {
  88205. var loc = 1;
  88206. while (!matrix[(x + loc) % arraySize]) {
  88207. loc++;
  88208. }
  88209. matrix[x] = matrix[(x + loc) % arraySize].slice();
  88210. //console.log("missing x", x);
  88211. }
  88212. for (var z = 0; z <= arraySize; ++z) {
  88213. if (!matrix[x][z]) {
  88214. var loc = 1;
  88215. var newValue;
  88216. while (newValue === undefined) {
  88217. newValue = matrix[x][(z + loc++) % arraySize];
  88218. }
  88219. matrix[x][z] = newValue;
  88220. }
  88221. }
  88222. }
  88223. var shape = new this.BJSCANNON.Heightfield(matrix, {
  88224. elementSize: elementSize
  88225. });
  88226. //For future reference, needed for body transformation
  88227. shape.minY = minY;
  88228. return shape;
  88229. };
  88230. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  88231. var object = impostor.object;
  88232. //make sure it is updated...
  88233. object.computeWorldMatrix && object.computeWorldMatrix(true);
  88234. // The delta between the mesh position and the mesh bounding box center
  88235. var bInfo = object.getBoundingInfo();
  88236. if (!bInfo)
  88237. return;
  88238. var center = impostor.getObjectCenter();
  88239. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  88240. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  88241. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  88242. this._tmpPosition.copyFrom(center);
  88243. var quaternion = object.rotationQuaternion;
  88244. if (!quaternion) {
  88245. return;
  88246. }
  88247. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88248. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88249. //-90 DEG in X, precalculated
  88250. quaternion = quaternion.multiply(this._minus90X);
  88251. //Invert! (Precalculated, 90 deg in X)
  88252. //No need to clone. this will never change.
  88253. impostor.setDeltaRotation(this._plus90X);
  88254. }
  88255. //If it is a heightfield, if should be centered.
  88256. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88257. var mesh = object;
  88258. var boundingInfo = mesh.getBoundingInfo();
  88259. //calculate the correct body position:
  88260. var rotationQuaternion = mesh.rotationQuaternion;
  88261. mesh.rotationQuaternion = this._tmpUnityRotation;
  88262. mesh.computeWorldMatrix(true);
  88263. //get original center with no rotation
  88264. var c = center.clone();
  88265. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88266. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88267. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88268. mesh.setPreTransformMatrix(p);
  88269. mesh.computeWorldMatrix(true);
  88270. //calculate the translation
  88271. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88272. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88273. //add it inverted to the delta
  88274. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88275. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88276. //rotation is back
  88277. mesh.rotationQuaternion = rotationQuaternion;
  88278. mesh.setPreTransformMatrix(oldPivot);
  88279. mesh.computeWorldMatrix(true);
  88280. }
  88281. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88282. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88283. //this._tmpPosition.copyFrom(object.position);
  88284. }
  88285. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88286. //Now update the impostor object
  88287. impostor.physicsBody.position.copy(this._tmpPosition);
  88288. impostor.physicsBody.quaternion.copy(quaternion);
  88289. };
  88290. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88291. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88292. if (impostor.object.rotationQuaternion) {
  88293. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88294. }
  88295. };
  88296. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88297. impostor.physicsBody.position.copy(newPosition);
  88298. impostor.physicsBody.quaternion.copy(newRotation);
  88299. };
  88300. CannonJSPlugin.prototype.isSupported = function () {
  88301. return this.BJSCANNON !== undefined;
  88302. };
  88303. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88304. impostor.physicsBody.velocity.copy(velocity);
  88305. };
  88306. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88307. impostor.physicsBody.angularVelocity.copy(velocity);
  88308. };
  88309. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88310. var v = impostor.physicsBody.velocity;
  88311. if (!v) {
  88312. return null;
  88313. }
  88314. return new BABYLON.Vector3(v.x, v.y, v.z);
  88315. };
  88316. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88317. var v = impostor.physicsBody.angularVelocity;
  88318. if (!v) {
  88319. return null;
  88320. }
  88321. return new BABYLON.Vector3(v.x, v.y, v.z);
  88322. };
  88323. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88324. impostor.physicsBody.mass = mass;
  88325. impostor.physicsBody.updateMassProperties();
  88326. };
  88327. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88328. return impostor.physicsBody.mass;
  88329. };
  88330. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88331. return impostor.physicsBody.material.friction;
  88332. };
  88333. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88334. impostor.physicsBody.material.friction = friction;
  88335. };
  88336. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88337. return impostor.physicsBody.material.restitution;
  88338. };
  88339. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88340. impostor.physicsBody.material.restitution = restitution;
  88341. };
  88342. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88343. impostor.physicsBody.sleep();
  88344. };
  88345. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88346. impostor.physicsBody.wakeUp();
  88347. };
  88348. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88349. joint.physicsJoint.distance = maxDistance;
  88350. };
  88351. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88352. // if (!motorIndex) {
  88353. // joint.physicsJoint.enableMotor();
  88354. // }
  88355. // }
  88356. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88357. // if (!motorIndex) {
  88358. // joint.physicsJoint.disableMotor();
  88359. // }
  88360. // }
  88361. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88362. if (!motorIndex) {
  88363. joint.physicsJoint.enableMotor();
  88364. joint.physicsJoint.setMotorSpeed(speed);
  88365. if (maxForce) {
  88366. this.setLimit(joint, maxForce);
  88367. }
  88368. }
  88369. };
  88370. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88371. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88372. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88373. };
  88374. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88375. var body = impostor.physicsBody;
  88376. mesh.position.x = body.position.x;
  88377. mesh.position.y = body.position.y;
  88378. mesh.position.z = body.position.z;
  88379. if (mesh.rotationQuaternion) {
  88380. mesh.rotationQuaternion.x = body.quaternion.x;
  88381. mesh.rotationQuaternion.y = body.quaternion.y;
  88382. mesh.rotationQuaternion.z = body.quaternion.z;
  88383. mesh.rotationQuaternion.w = body.quaternion.w;
  88384. }
  88385. };
  88386. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88387. var shape = impostor.physicsBody.shapes[0];
  88388. return shape.boundingSphereRadius;
  88389. };
  88390. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88391. var shape = impostor.physicsBody.shapes[0];
  88392. result.x = shape.halfExtents.x * 2;
  88393. result.y = shape.halfExtents.y * 2;
  88394. result.z = shape.halfExtents.z * 2;
  88395. };
  88396. CannonJSPlugin.prototype.dispose = function () {
  88397. };
  88398. CannonJSPlugin.prototype._extendNamespace = function () {
  88399. //this will force cannon to execute at least one step when using interpolation
  88400. var step_tmp1 = new this.BJSCANNON.Vec3();
  88401. var Engine = this.BJSCANNON;
  88402. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88403. maxSubSteps = maxSubSteps || 10;
  88404. timeSinceLastCalled = timeSinceLastCalled || 0;
  88405. if (timeSinceLastCalled === 0) {
  88406. this.internalStep(dt);
  88407. this.time += dt;
  88408. }
  88409. else {
  88410. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88411. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88412. var t0 = performance.now();
  88413. for (var i = 0; i !== internalSteps; i++) {
  88414. this.internalStep(dt);
  88415. if (performance.now() - t0 > dt * 1000) {
  88416. break;
  88417. }
  88418. }
  88419. this.time += timeSinceLastCalled;
  88420. var h = this.time % dt;
  88421. var h_div_dt = h / dt;
  88422. var interpvelo = step_tmp1;
  88423. var bodies = this.bodies;
  88424. for (var j = 0; j !== bodies.length; j++) {
  88425. var b = bodies[j];
  88426. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88427. b.position.vsub(b.previousPosition, interpvelo);
  88428. interpvelo.scale(h_div_dt, interpvelo);
  88429. b.position.vadd(interpvelo, b.interpolatedPosition);
  88430. }
  88431. else {
  88432. b.interpolatedPosition.copy(b.position);
  88433. b.interpolatedQuaternion.copy(b.quaternion);
  88434. }
  88435. }
  88436. }
  88437. };
  88438. };
  88439. return CannonJSPlugin;
  88440. }());
  88441. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88442. })(BABYLON || (BABYLON = {}));
  88443. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88444. var BABYLON;
  88445. (function (BABYLON) {
  88446. var OimoJSPlugin = /** @class */ (function () {
  88447. function OimoJSPlugin(iterations) {
  88448. this.name = "OimoJSPlugin";
  88449. this._tmpImpostorsArray = [];
  88450. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88451. this.BJSOIMO = OIMO;
  88452. this.world = new this.BJSOIMO.World({
  88453. iterations: iterations
  88454. });
  88455. this.world.clear();
  88456. }
  88457. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88458. this.world.gravity.copy(gravity);
  88459. };
  88460. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88461. this.world.timeStep = timeStep;
  88462. };
  88463. OimoJSPlugin.prototype.getTimeStep = function () {
  88464. return this.world.timeStep;
  88465. };
  88466. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88467. var _this = this;
  88468. impostors.forEach(function (impostor) {
  88469. impostor.beforeStep();
  88470. });
  88471. this.world.step();
  88472. impostors.forEach(function (impostor) {
  88473. impostor.afterStep();
  88474. //update the ordered impostors array
  88475. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88476. });
  88477. //check for collisions
  88478. var contact = this.world.contacts;
  88479. while (contact !== null) {
  88480. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88481. contact = contact.next;
  88482. continue;
  88483. }
  88484. //is this body colliding with any other? get the impostor
  88485. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88486. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88487. if (!mainImpostor || !collidingImpostor) {
  88488. contact = contact.next;
  88489. continue;
  88490. }
  88491. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88492. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88493. contact = contact.next;
  88494. }
  88495. };
  88496. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88497. var mass = impostor.physicsBody.mass;
  88498. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88499. };
  88500. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88501. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88502. this.applyImpulse(impostor, force, contactPoint);
  88503. };
  88504. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88505. var _this = this;
  88506. //parent-child relationship. Does this impostor has a parent impostor?
  88507. if (impostor.parent) {
  88508. if (impostor.physicsBody) {
  88509. this.removePhysicsBody(impostor);
  88510. //TODO is that needed?
  88511. impostor.forceUpdate();
  88512. }
  88513. return;
  88514. }
  88515. if (impostor.isBodyInitRequired()) {
  88516. var bodyConfig = {
  88517. name: impostor.uniqueId,
  88518. //Oimo must have mass, also for static objects.
  88519. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  88520. size: [],
  88521. type: [],
  88522. pos: [],
  88523. posShape: [],
  88524. rot: [],
  88525. rotShape: [],
  88526. move: impostor.getParam("mass") !== 0,
  88527. density: impostor.getParam("mass"),
  88528. friction: impostor.getParam("friction"),
  88529. restitution: impostor.getParam("restitution"),
  88530. //Supporting older versions of Oimo
  88531. world: this.world
  88532. };
  88533. var impostors = [impostor];
  88534. var addToArray = function (parent) {
  88535. if (!parent.getChildMeshes)
  88536. return;
  88537. parent.getChildMeshes().forEach(function (m) {
  88538. if (m.physicsImpostor) {
  88539. impostors.push(m.physicsImpostor);
  88540. //m.physicsImpostor._init();
  88541. }
  88542. });
  88543. };
  88544. addToArray(impostor.object);
  88545. var checkWithEpsilon_1 = function (value) {
  88546. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  88547. };
  88548. var globalQuaternion_1 = new BABYLON.Quaternion();
  88549. impostors.forEach(function (i) {
  88550. if (!i.object.rotationQuaternion) {
  88551. return;
  88552. }
  88553. //get the correct bounding box
  88554. var oldQuaternion = i.object.rotationQuaternion;
  88555. globalQuaternion_1 = oldQuaternion.clone();
  88556. var rot = oldQuaternion.toEulerAngles();
  88557. var extendSize = i.getObjectExtendSize();
  88558. var radToDeg = 57.295779513082320876;
  88559. if (i === impostor) {
  88560. var center = impostor.getObjectCenter();
  88561. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  88562. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  88563. //Can also use Array.prototype.push.apply
  88564. bodyConfig.pos.push(center.x);
  88565. bodyConfig.pos.push(center.y);
  88566. bodyConfig.pos.push(center.z);
  88567. bodyConfig.posShape.push(0, 0, 0);
  88568. //tmp solution
  88569. bodyConfig.rot.push(0);
  88570. bodyConfig.rot.push(0);
  88571. bodyConfig.rot.push(0);
  88572. bodyConfig.rotShape.push(0, 0, 0);
  88573. }
  88574. else {
  88575. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  88576. bodyConfig.posShape.push(localPosition.x);
  88577. bodyConfig.posShape.push(localPosition.y);
  88578. bodyConfig.posShape.push(localPosition.z);
  88579. bodyConfig.pos.push(0, 0, 0);
  88580. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  88581. bodyConfig.rot.push(0);
  88582. bodyConfig.rot.push(0);
  88583. bodyConfig.rot.push(0);
  88584. bodyConfig.rotShape.push(rot.x * radToDeg);
  88585. bodyConfig.rotShape.push(rot.y * radToDeg);
  88586. bodyConfig.rotShape.push(rot.z * radToDeg);
  88587. }
  88588. // register mesh
  88589. switch (i.type) {
  88590. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88591. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  88592. case BABYLON.PhysicsImpostor.SphereImpostor:
  88593. var radiusX = extendSize.x;
  88594. var radiusY = extendSize.y;
  88595. var radiusZ = extendSize.z;
  88596. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  88597. bodyConfig.type.push('sphere');
  88598. //due to the way oimo works with compounds, add 3 times
  88599. bodyConfig.size.push(size);
  88600. bodyConfig.size.push(size);
  88601. bodyConfig.size.push(size);
  88602. break;
  88603. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88604. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  88605. var sizeY = checkWithEpsilon_1(extendSize.y);
  88606. bodyConfig.type.push('cylinder');
  88607. bodyConfig.size.push(sizeX);
  88608. bodyConfig.size.push(sizeY);
  88609. //due to the way oimo works with compounds, add one more value.
  88610. bodyConfig.size.push(sizeY);
  88611. break;
  88612. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88613. case BABYLON.PhysicsImpostor.BoxImpostor:
  88614. default:
  88615. var sizeX = checkWithEpsilon_1(extendSize.x);
  88616. var sizeY = checkWithEpsilon_1(extendSize.y);
  88617. var sizeZ = checkWithEpsilon_1(extendSize.z);
  88618. bodyConfig.type.push('box');
  88619. //if (i === impostor) {
  88620. bodyConfig.size.push(sizeX);
  88621. bodyConfig.size.push(sizeY);
  88622. bodyConfig.size.push(sizeZ);
  88623. //} else {
  88624. // bodyConfig.size.push(0,0,0);
  88625. //}
  88626. break;
  88627. }
  88628. //actually not needed, but hey...
  88629. i.object.rotationQuaternion = oldQuaternion;
  88630. });
  88631. impostor.physicsBody = this.world.add(bodyConfig);
  88632. // set the quaternion, ignoring the previously defined (euler) rotation
  88633. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  88634. // update with delta 0, so the body will reveive the new rotation.
  88635. impostor.physicsBody.updatePosition(0);
  88636. }
  88637. else {
  88638. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  88639. }
  88640. impostor.setDeltaPosition(this._tmpPositionVector);
  88641. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  88642. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  88643. };
  88644. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88645. //impostor.physicsBody.dispose();
  88646. //Same as : (older oimo versions)
  88647. this.world.removeRigidBody(impostor.physicsBody);
  88648. };
  88649. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88650. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88651. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88652. if (!mainBody || !connectedBody) {
  88653. return;
  88654. }
  88655. var jointData = impostorJoint.joint.jointData;
  88656. var options = jointData.nativeParams || {};
  88657. var type;
  88658. var nativeJointData = {
  88659. body1: mainBody,
  88660. body2: connectedBody,
  88661. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  88662. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  88663. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  88664. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  88665. min: options.min,
  88666. max: options.max,
  88667. collision: options.collision || jointData.collision,
  88668. spring: options.spring,
  88669. //supporting older version of Oimo
  88670. world: this.world
  88671. };
  88672. switch (impostorJoint.joint.type) {
  88673. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88674. type = "jointBall";
  88675. break;
  88676. case BABYLON.PhysicsJoint.SpringJoint:
  88677. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  88678. var springData = jointData;
  88679. nativeJointData.min = springData.length || nativeJointData.min;
  88680. //Max should also be set, just make sure it is at least min
  88681. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  88682. case BABYLON.PhysicsJoint.DistanceJoint:
  88683. type = "jointDistance";
  88684. nativeJointData.max = jointData.maxDistance;
  88685. break;
  88686. case BABYLON.PhysicsJoint.PrismaticJoint:
  88687. type = "jointPrisme";
  88688. break;
  88689. case BABYLON.PhysicsJoint.SliderJoint:
  88690. type = "jointSlide";
  88691. break;
  88692. case BABYLON.PhysicsJoint.WheelJoint:
  88693. type = "jointWheel";
  88694. break;
  88695. case BABYLON.PhysicsJoint.HingeJoint:
  88696. default:
  88697. type = "jointHinge";
  88698. break;
  88699. }
  88700. nativeJointData.type = type;
  88701. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  88702. };
  88703. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88704. //Bug in Oimo prevents us from disposing a joint in the playground
  88705. //joint.joint.physicsJoint.dispose();
  88706. //So we will bruteforce it!
  88707. try {
  88708. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  88709. }
  88710. catch (e) {
  88711. BABYLON.Tools.Warn(e);
  88712. }
  88713. };
  88714. OimoJSPlugin.prototype.isSupported = function () {
  88715. return this.BJSOIMO !== undefined;
  88716. };
  88717. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88718. if (!impostor.physicsBody.sleeping) {
  88719. //TODO check that
  88720. /*if (impostor.physicsBody.shapes.next) {
  88721. var parentShape = this._getLastShape(impostor.physicsBody);
  88722. impostor.object.position.copyFrom(parentShape.position);
  88723. console.log(parentShape.position);
  88724. } else {*/
  88725. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  88726. //}
  88727. if (impostor.object.rotationQuaternion) {
  88728. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  88729. }
  88730. }
  88731. };
  88732. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88733. var body = impostor.physicsBody;
  88734. body.position.copy(newPosition);
  88735. body.orientation.copy(newRotation);
  88736. body.syncShapes();
  88737. body.awake();
  88738. };
  88739. /*private _getLastShape(body: any): any {
  88740. var lastShape = body.shapes;
  88741. while (lastShape.next) {
  88742. lastShape = lastShape.next;
  88743. }
  88744. return lastShape;
  88745. }*/
  88746. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88747. impostor.physicsBody.linearVelocity.copy(velocity);
  88748. };
  88749. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88750. impostor.physicsBody.angularVelocity.copy(velocity);
  88751. };
  88752. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88753. var v = impostor.physicsBody.linearVelocity;
  88754. if (!v) {
  88755. return null;
  88756. }
  88757. return new BABYLON.Vector3(v.x, v.y, v.z);
  88758. };
  88759. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88760. var v = impostor.physicsBody.angularVelocity;
  88761. if (!v) {
  88762. return null;
  88763. }
  88764. return new BABYLON.Vector3(v.x, v.y, v.z);
  88765. };
  88766. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88767. var staticBody = mass === 0;
  88768. //this will actually set the body's density and not its mass.
  88769. //But this is how oimo treats the mass variable.
  88770. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  88771. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  88772. };
  88773. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  88774. return impostor.physicsBody.shapes.density;
  88775. };
  88776. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  88777. return impostor.physicsBody.shapes.friction;
  88778. };
  88779. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88780. impostor.physicsBody.shapes.friction = friction;
  88781. };
  88782. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88783. return impostor.physicsBody.shapes.restitution;
  88784. };
  88785. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88786. impostor.physicsBody.shapes.restitution = restitution;
  88787. };
  88788. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  88789. impostor.physicsBody.sleep();
  88790. };
  88791. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  88792. impostor.physicsBody.awake();
  88793. };
  88794. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88795. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  88796. if (minDistance !== void 0) {
  88797. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  88798. }
  88799. };
  88800. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88801. //TODO separate rotational and transational motors.
  88802. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  88803. if (motor) {
  88804. motor.setMotor(speed, maxForce);
  88805. }
  88806. };
  88807. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  88808. //TODO separate rotational and transational motors.
  88809. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  88810. if (motor) {
  88811. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  88812. }
  88813. };
  88814. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88815. var body = impostor.physicsBody;
  88816. mesh.position.x = body.position.x;
  88817. mesh.position.y = body.position.y;
  88818. mesh.position.z = body.position.z;
  88819. if (mesh.rotationQuaternion) {
  88820. mesh.rotationQuaternion.x = body.orientation.x;
  88821. mesh.rotationQuaternion.y = body.orientation.y;
  88822. mesh.rotationQuaternion.z = body.orientation.z;
  88823. mesh.rotationQuaternion.w = body.orientation.s;
  88824. }
  88825. };
  88826. OimoJSPlugin.prototype.getRadius = function (impostor) {
  88827. return impostor.physicsBody.shapes.radius;
  88828. };
  88829. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88830. var shape = impostor.physicsBody.shapes;
  88831. result.x = shape.halfWidth * 2;
  88832. result.y = shape.halfHeight * 2;
  88833. result.z = shape.halfDepth * 2;
  88834. };
  88835. OimoJSPlugin.prototype.dispose = function () {
  88836. this.world.clear();
  88837. };
  88838. return OimoJSPlugin;
  88839. }());
  88840. BABYLON.OimoJSPlugin = OimoJSPlugin;
  88841. })(BABYLON || (BABYLON = {}));
  88842. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  88843. var BABYLON;
  88844. (function (BABYLON) {
  88845. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  88846. // All values and structures referenced from:
  88847. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  88848. var DDS_MAGIC = 0x20534444;
  88849. var
  88850. //DDSD_CAPS = 0x1,
  88851. //DDSD_HEIGHT = 0x2,
  88852. //DDSD_WIDTH = 0x4,
  88853. //DDSD_PITCH = 0x8,
  88854. //DDSD_PIXELFORMAT = 0x1000,
  88855. DDSD_MIPMAPCOUNT = 0x20000;
  88856. //DDSD_LINEARSIZE = 0x80000,
  88857. //DDSD_DEPTH = 0x800000;
  88858. // var DDSCAPS_COMPLEX = 0x8,
  88859. // DDSCAPS_MIPMAP = 0x400000,
  88860. // DDSCAPS_TEXTURE = 0x1000;
  88861. var DDSCAPS2_CUBEMAP = 0x200;
  88862. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  88863. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  88864. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  88865. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  88866. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  88867. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  88868. // DDSCAPS2_VOLUME = 0x200000;
  88869. var
  88870. //DDPF_ALPHAPIXELS = 0x1,
  88871. //DDPF_ALPHA = 0x2,
  88872. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  88873. //DDPF_YUV = 0x200,
  88874. DDPF_LUMINANCE = 0x20000;
  88875. function FourCCToInt32(value) {
  88876. return value.charCodeAt(0) +
  88877. (value.charCodeAt(1) << 8) +
  88878. (value.charCodeAt(2) << 16) +
  88879. (value.charCodeAt(3) << 24);
  88880. }
  88881. function Int32ToFourCC(value) {
  88882. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  88883. }
  88884. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  88885. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  88886. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  88887. var FOURCC_DX10 = FourCCToInt32("DX10");
  88888. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  88889. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  88890. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  88891. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  88892. var headerLengthInt = 31; // The header length in 32 bit ints
  88893. // Offsets into the header array
  88894. var off_magic = 0;
  88895. var off_size = 1;
  88896. var off_flags = 2;
  88897. var off_height = 3;
  88898. var off_width = 4;
  88899. var off_mipmapCount = 7;
  88900. var off_pfFlags = 20;
  88901. var off_pfFourCC = 21;
  88902. var off_RGBbpp = 22;
  88903. var off_RMask = 23;
  88904. var off_GMask = 24;
  88905. var off_BMask = 25;
  88906. var off_AMask = 26;
  88907. // var off_caps1 = 27;
  88908. var off_caps2 = 28;
  88909. // var off_caps3 = 29;
  88910. // var off_caps4 = 30;
  88911. var off_dxgiFormat = 32;
  88912. ;
  88913. var DDSTools = /** @class */ (function () {
  88914. function DDSTools() {
  88915. }
  88916. DDSTools.GetDDSInfo = function (arrayBuffer) {
  88917. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88918. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  88919. var mipmapCount = 1;
  88920. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  88921. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88922. }
  88923. var fourCC = header[off_pfFourCC];
  88924. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  88925. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88926. switch (fourCC) {
  88927. case FOURCC_D3DFMT_R16G16B16A16F:
  88928. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88929. break;
  88930. case FOURCC_D3DFMT_R32G32B32A32F:
  88931. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88932. break;
  88933. case FOURCC_DX10:
  88934. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  88935. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88936. break;
  88937. }
  88938. }
  88939. return {
  88940. width: header[off_width],
  88941. height: header[off_height],
  88942. mipmapCount: mipmapCount,
  88943. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  88944. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  88945. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  88946. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  88947. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  88948. dxgiFormat: dxgiFormat,
  88949. textureType: textureType
  88950. };
  88951. };
  88952. DDSTools._ToHalfFloat = function (value) {
  88953. if (!DDSTools._FloatView) {
  88954. DDSTools._FloatView = new Float32Array(1);
  88955. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  88956. }
  88957. DDSTools._FloatView[0] = value;
  88958. var x = DDSTools._Int32View[0];
  88959. var bits = (x >> 16) & 0x8000; /* Get the sign */
  88960. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  88961. var e = (x >> 23) & 0xff; /* Using int is faster here */
  88962. /* If zero, or denormal, or exponent underflows too much for a denormal
  88963. * half, return signed zero. */
  88964. if (e < 103) {
  88965. return bits;
  88966. }
  88967. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  88968. if (e > 142) {
  88969. bits |= 0x7c00;
  88970. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  88971. * not Inf, so make sure we set one mantissa bit too. */
  88972. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  88973. return bits;
  88974. }
  88975. /* If exponent underflows but not too much, return a denormal */
  88976. if (e < 113) {
  88977. m |= 0x0800;
  88978. /* Extra rounding may overflow and set mantissa to 0 and exponent
  88979. * to 1, which is OK. */
  88980. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  88981. return bits;
  88982. }
  88983. bits |= ((e - 112) << 10) | (m >> 1);
  88984. bits += m & 1;
  88985. return bits;
  88986. };
  88987. DDSTools._FromHalfFloat = function (value) {
  88988. var s = (value & 0x8000) >> 15;
  88989. var e = (value & 0x7C00) >> 10;
  88990. var f = value & 0x03FF;
  88991. if (e === 0) {
  88992. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  88993. }
  88994. else if (e == 0x1F) {
  88995. return f ? NaN : ((s ? -1 : 1) * Infinity);
  88996. }
  88997. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  88998. };
  88999. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89000. var destArray = new Float32Array(dataLength);
  89001. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89002. var index = 0;
  89003. for (var y = 0; y < height; y++) {
  89004. for (var x = 0; x < width; x++) {
  89005. var srcPos = (x + y * width) * 4;
  89006. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89007. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89008. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89009. if (DDSTools.StoreLODInAlphaChannel) {
  89010. destArray[index + 3] = lod;
  89011. }
  89012. else {
  89013. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89014. }
  89015. index += 4;
  89016. }
  89017. }
  89018. return destArray;
  89019. };
  89020. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89021. if (DDSTools.StoreLODInAlphaChannel) {
  89022. var destArray = new Uint16Array(dataLength);
  89023. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89024. var index = 0;
  89025. for (var y = 0; y < height; y++) {
  89026. for (var x = 0; x < width; x++) {
  89027. var srcPos = (x + y * width) * 4;
  89028. destArray[index] = srcData[srcPos];
  89029. destArray[index + 1] = srcData[srcPos + 1];
  89030. destArray[index + 2] = srcData[srcPos + 2];
  89031. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89032. index += 4;
  89033. }
  89034. }
  89035. return destArray;
  89036. }
  89037. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89038. };
  89039. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89040. if (DDSTools.StoreLODInAlphaChannel) {
  89041. var destArray = new Float32Array(dataLength);
  89042. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89043. var index = 0;
  89044. for (var y = 0; y < height; y++) {
  89045. for (var x = 0; x < width; x++) {
  89046. var srcPos = (x + y * width) * 4;
  89047. destArray[index] = srcData[srcPos];
  89048. destArray[index + 1] = srcData[srcPos + 1];
  89049. destArray[index + 2] = srcData[srcPos + 2];
  89050. destArray[index + 3] = lod;
  89051. index += 4;
  89052. }
  89053. }
  89054. return destArray;
  89055. }
  89056. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89057. };
  89058. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89059. var destArray = new Uint8Array(dataLength);
  89060. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89061. var index = 0;
  89062. for (var y = 0; y < height; y++) {
  89063. for (var x = 0; x < width; x++) {
  89064. var srcPos = (x + y * width) * 4;
  89065. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89066. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89067. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89068. if (DDSTools.StoreLODInAlphaChannel) {
  89069. destArray[index + 3] = lod;
  89070. }
  89071. else {
  89072. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89073. }
  89074. index += 4;
  89075. }
  89076. }
  89077. return destArray;
  89078. };
  89079. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89080. var destArray = new Uint8Array(dataLength);
  89081. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89082. var index = 0;
  89083. for (var y = 0; y < height; y++) {
  89084. for (var x = 0; x < width; x++) {
  89085. var srcPos = (x + y * width) * 4;
  89086. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  89087. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  89088. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  89089. if (DDSTools.StoreLODInAlphaChannel) {
  89090. destArray[index + 3] = lod;
  89091. }
  89092. else {
  89093. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  89094. }
  89095. index += 4;
  89096. }
  89097. }
  89098. return destArray;
  89099. };
  89100. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  89101. var byteArray = new Uint8Array(dataLength);
  89102. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89103. var index = 0;
  89104. for (var y = 0; y < height; y++) {
  89105. for (var x = 0; x < width; x++) {
  89106. var srcPos = (x + y * width) * 4;
  89107. byteArray[index] = srcData[srcPos + rOffset];
  89108. byteArray[index + 1] = srcData[srcPos + gOffset];
  89109. byteArray[index + 2] = srcData[srcPos + bOffset];
  89110. byteArray[index + 3] = srcData[srcPos + aOffset];
  89111. index += 4;
  89112. }
  89113. }
  89114. return byteArray;
  89115. };
  89116. DDSTools._ExtractLongWordOrder = function (value) {
  89117. if (value === 0 || value === 255 || value === -16777216) {
  89118. return 0;
  89119. }
  89120. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  89121. };
  89122. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  89123. var byteArray = new Uint8Array(dataLength);
  89124. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89125. var index = 0;
  89126. for (var y = 0; y < height; y++) {
  89127. for (var x = 0; x < width; x++) {
  89128. var srcPos = (x + y * width) * 3;
  89129. byteArray[index] = srcData[srcPos + rOffset];
  89130. byteArray[index + 1] = srcData[srcPos + gOffset];
  89131. byteArray[index + 2] = srcData[srcPos + bOffset];
  89132. index += 3;
  89133. }
  89134. }
  89135. return byteArray;
  89136. };
  89137. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  89138. var byteArray = new Uint8Array(dataLength);
  89139. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89140. var index = 0;
  89141. for (var y = 0; y < height; y++) {
  89142. for (var x = 0; x < width; x++) {
  89143. var srcPos = (x + y * width);
  89144. byteArray[index] = srcData[srcPos];
  89145. index++;
  89146. }
  89147. }
  89148. return byteArray;
  89149. };
  89150. /**
  89151. * Uploads DDS Levels to a Babylon Texture
  89152. * @hidden
  89153. */
  89154. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  89155. if (lodIndex === void 0) { lodIndex = -1; }
  89156. var sphericalPolynomialFaces = null;
  89157. if (info.sphericalPolynomial) {
  89158. sphericalPolynomialFaces = new Array();
  89159. }
  89160. var ext = engine.getCaps().s3tc;
  89161. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89162. var fourCC, width, height, dataLength = 0, dataOffset;
  89163. var byteArray, mipmapCount, mip;
  89164. var internalCompressedFormat = 0;
  89165. var blockBytes = 1;
  89166. if (header[off_magic] !== DDS_MAGIC) {
  89167. BABYLON.Tools.Error("Invalid magic number in DDS header");
  89168. return;
  89169. }
  89170. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  89171. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  89172. return;
  89173. }
  89174. if (info.isCompressed && !ext) {
  89175. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  89176. return;
  89177. }
  89178. var bpp = header[off_RGBbpp];
  89179. dataOffset = header[off_size] + 4;
  89180. var computeFormats = false;
  89181. if (info.isFourCC) {
  89182. fourCC = header[off_pfFourCC];
  89183. switch (fourCC) {
  89184. case FOURCC_DXT1:
  89185. blockBytes = 8;
  89186. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  89187. break;
  89188. case FOURCC_DXT3:
  89189. blockBytes = 16;
  89190. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  89191. break;
  89192. case FOURCC_DXT5:
  89193. blockBytes = 16;
  89194. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  89195. break;
  89196. case FOURCC_D3DFMT_R16G16B16A16F:
  89197. computeFormats = true;
  89198. break;
  89199. case FOURCC_D3DFMT_R32G32B32A32F:
  89200. computeFormats = true;
  89201. break;
  89202. case FOURCC_DX10:
  89203. // There is an additionnal header so dataOffset need to be changed
  89204. dataOffset += 5 * 4; // 5 uints
  89205. var supported = false;
  89206. switch (info.dxgiFormat) {
  89207. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  89208. computeFormats = true;
  89209. supported = true;
  89210. break;
  89211. case DXGI_FORMAT_B8G8R8X8_UNORM:
  89212. info.isRGB = true;
  89213. info.isFourCC = false;
  89214. bpp = 32;
  89215. supported = true;
  89216. break;
  89217. }
  89218. if (supported) {
  89219. break;
  89220. }
  89221. default:
  89222. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  89223. return;
  89224. }
  89225. }
  89226. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  89227. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  89228. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  89229. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  89230. if (computeFormats) {
  89231. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  89232. }
  89233. mipmapCount = 1;
  89234. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  89235. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89236. }
  89237. for (var face = 0; face < faces; face++) {
  89238. width = header[off_width];
  89239. height = header[off_height];
  89240. for (mip = 0; mip < mipmapCount; ++mip) {
  89241. if (lodIndex === -1 || lodIndex === mip) {
  89242. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  89243. var i = (lodIndex === -1) ? mip : 0;
  89244. if (!info.isCompressed && info.isFourCC) {
  89245. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89246. dataLength = width * height * 4;
  89247. var floatArray = null;
  89248. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89249. if (bpp === 128) {
  89250. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89251. if (sphericalPolynomialFaces && i == 0) {
  89252. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89253. }
  89254. }
  89255. else if (bpp === 64) {
  89256. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89257. if (sphericalPolynomialFaces && i == 0) {
  89258. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89259. }
  89260. }
  89261. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89262. }
  89263. else {
  89264. if (bpp === 128) {
  89265. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89266. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89267. if (sphericalPolynomialFaces && i == 0) {
  89268. sphericalPolynomialFaces.push(floatArray);
  89269. }
  89270. }
  89271. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89272. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89273. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89274. if (sphericalPolynomialFaces && i == 0) {
  89275. sphericalPolynomialFaces.push(floatArray);
  89276. }
  89277. }
  89278. else { // 64
  89279. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89280. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89281. if (sphericalPolynomialFaces && i == 0) {
  89282. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89283. }
  89284. }
  89285. }
  89286. if (floatArray) {
  89287. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89288. }
  89289. }
  89290. else if (info.isRGB) {
  89291. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89292. if (bpp === 24) {
  89293. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89294. dataLength = width * height * 3;
  89295. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89296. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89297. }
  89298. else { // 32
  89299. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89300. dataLength = width * height * 4;
  89301. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89302. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89303. }
  89304. }
  89305. else if (info.isLuminance) {
  89306. var unpackAlignment = engine._getUnpackAlignement();
  89307. var unpaddedRowSize = width;
  89308. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89309. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89310. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89311. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89312. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89313. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89314. }
  89315. else {
  89316. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89317. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89318. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89319. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89320. }
  89321. }
  89322. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89323. width *= 0.5;
  89324. height *= 0.5;
  89325. width = Math.max(1.0, width);
  89326. height = Math.max(1.0, height);
  89327. }
  89328. if (currentFace !== undefined) {
  89329. // Loading a single face
  89330. break;
  89331. }
  89332. }
  89333. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89334. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89335. size: header[off_width],
  89336. right: sphericalPolynomialFaces[0],
  89337. left: sphericalPolynomialFaces[1],
  89338. up: sphericalPolynomialFaces[2],
  89339. down: sphericalPolynomialFaces[3],
  89340. front: sphericalPolynomialFaces[4],
  89341. back: sphericalPolynomialFaces[5],
  89342. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89343. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89344. gammaSpace: false,
  89345. });
  89346. }
  89347. else {
  89348. info.sphericalPolynomial = undefined;
  89349. }
  89350. };
  89351. DDSTools.StoreLODInAlphaChannel = false;
  89352. return DDSTools;
  89353. }());
  89354. BABYLON.DDSTools = DDSTools;
  89355. })(BABYLON || (BABYLON = {}));
  89356. //# sourceMappingURL=babylon.dds.js.map
  89357. var BABYLON;
  89358. (function (BABYLON) {
  89359. /**
  89360. * Implementation of the DDS Texture Loader.
  89361. */
  89362. var DDSTextureLoader = /** @class */ (function () {
  89363. function DDSTextureLoader() {
  89364. /**
  89365. * Defines wether the loader supports cascade loading the different faces.
  89366. */
  89367. this.supportCascades = true;
  89368. }
  89369. /**
  89370. * This returns if the loader support the current file information.
  89371. * @param extension defines the file extension of the file being loaded
  89372. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89373. * @param fallback defines the fallback internal texture if any
  89374. * @param isBase64 defines whether the texture is encoded as a base64
  89375. * @param isBuffer defines whether the texture data are stored as a buffer
  89376. * @returns true if the loader can load the specified file
  89377. */
  89378. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89379. return extension.indexOf(".dds") === 0;
  89380. };
  89381. /**
  89382. * Transform the url before loading if required.
  89383. * @param rootUrl the url of the texture
  89384. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89385. * @returns the transformed texture
  89386. */
  89387. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89388. return rootUrl;
  89389. };
  89390. /**
  89391. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89392. * @param rootUrl the url of the texture
  89393. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89394. * @returns the fallback texture
  89395. */
  89396. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89397. return null;
  89398. };
  89399. /**
  89400. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89401. * @param data contains the texture data
  89402. * @param texture defines the BabylonJS internal texture
  89403. * @param createPolynomials will be true if polynomials have been requested
  89404. * @param onLoad defines the callback to trigger once the texture is ready
  89405. * @param onError defines the callback to trigger in case of error
  89406. */
  89407. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89408. var engine = texture.getEngine();
  89409. var info;
  89410. var loadMipmap = false;
  89411. if (Array.isArray(imgs)) {
  89412. for (var index = 0; index < imgs.length; index++) {
  89413. var data_1 = imgs[index];
  89414. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89415. texture.width = info.width;
  89416. texture.height = info.height;
  89417. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89418. engine._unpackFlipY(info.isCompressed);
  89419. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89420. if (!info.isFourCC && info.mipmapCount === 1) {
  89421. engine.generateMipMapsForCubemap(texture);
  89422. }
  89423. }
  89424. }
  89425. else {
  89426. var data = imgs;
  89427. info = BABYLON.DDSTools.GetDDSInfo(data);
  89428. texture.width = info.width;
  89429. texture.height = info.height;
  89430. if (createPolynomials) {
  89431. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89432. }
  89433. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89434. engine._unpackFlipY(info.isCompressed);
  89435. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89436. if (!info.isFourCC && info.mipmapCount === 1) {
  89437. engine.generateMipMapsForCubemap(texture);
  89438. }
  89439. }
  89440. engine._setCubeMapTextureParams(loadMipmap);
  89441. texture.isReady = true;
  89442. if (onLoad) {
  89443. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89444. }
  89445. };
  89446. /**
  89447. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89448. * @param data contains the texture data
  89449. * @param texture defines the BabylonJS internal texture
  89450. * @param callback defines the method to call once ready to upload
  89451. */
  89452. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89453. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89454. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89455. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89456. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89457. });
  89458. };
  89459. return DDSTextureLoader;
  89460. }());
  89461. // Register the loader.
  89462. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89463. })(BABYLON || (BABYLON = {}));
  89464. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89465. var BABYLON;
  89466. (function (BABYLON) {
  89467. /*
  89468. * Based on jsTGALoader - Javascript loader for TGA file
  89469. * By Vincent Thibault
  89470. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89471. */
  89472. var TGATools = /** @class */ (function () {
  89473. function TGATools() {
  89474. }
  89475. TGATools.GetTGAHeader = function (data) {
  89476. var offset = 0;
  89477. var header = {
  89478. id_length: data[offset++],
  89479. colormap_type: data[offset++],
  89480. image_type: data[offset++],
  89481. colormap_index: data[offset++] | data[offset++] << 8,
  89482. colormap_length: data[offset++] | data[offset++] << 8,
  89483. colormap_size: data[offset++],
  89484. origin: [
  89485. data[offset++] | data[offset++] << 8,
  89486. data[offset++] | data[offset++] << 8
  89487. ],
  89488. width: data[offset++] | data[offset++] << 8,
  89489. height: data[offset++] | data[offset++] << 8,
  89490. pixel_size: data[offset++],
  89491. flags: data[offset++]
  89492. };
  89493. return header;
  89494. };
  89495. /**
  89496. * Uploads TGA content to a Babylon Texture
  89497. * @hidden
  89498. */
  89499. TGATools.UploadContent = function (texture, data) {
  89500. // Not enough data to contain header ?
  89501. if (data.length < 19) {
  89502. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89503. return;
  89504. }
  89505. // Read Header
  89506. var offset = 18;
  89507. var header = TGATools.GetTGAHeader(data);
  89508. // Assume it's a valid Targa file.
  89509. if (header.id_length + offset > data.length) {
  89510. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89511. return;
  89512. }
  89513. // Skip not needed data
  89514. offset += header.id_length;
  89515. var use_rle = false;
  89516. var use_pal = false;
  89517. var use_grey = false;
  89518. // Get some informations.
  89519. switch (header.image_type) {
  89520. case TGATools._TYPE_RLE_INDEXED:
  89521. use_rle = true;
  89522. case TGATools._TYPE_INDEXED:
  89523. use_pal = true;
  89524. break;
  89525. case TGATools._TYPE_RLE_RGB:
  89526. use_rle = true;
  89527. case TGATools._TYPE_RGB:
  89528. // use_rgb = true;
  89529. break;
  89530. case TGATools._TYPE_RLE_GREY:
  89531. use_rle = true;
  89532. case TGATools._TYPE_GREY:
  89533. use_grey = true;
  89534. break;
  89535. }
  89536. var pixel_data;
  89537. // var numAlphaBits = header.flags & 0xf;
  89538. var pixel_size = header.pixel_size >> 3;
  89539. var pixel_total = header.width * header.height * pixel_size;
  89540. // Read palettes
  89541. var palettes;
  89542. if (use_pal) {
  89543. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  89544. }
  89545. // Read LRE
  89546. if (use_rle) {
  89547. pixel_data = new Uint8Array(pixel_total);
  89548. var c, count, i;
  89549. var localOffset = 0;
  89550. var pixels = new Uint8Array(pixel_size);
  89551. while (offset < pixel_total && localOffset < pixel_total) {
  89552. c = data[offset++];
  89553. count = (c & 0x7f) + 1;
  89554. // RLE pixels
  89555. if (c & 0x80) {
  89556. // Bind pixel tmp array
  89557. for (i = 0; i < pixel_size; ++i) {
  89558. pixels[i] = data[offset++];
  89559. }
  89560. // Copy pixel array
  89561. for (i = 0; i < count; ++i) {
  89562. pixel_data.set(pixels, localOffset + i * pixel_size);
  89563. }
  89564. localOffset += pixel_size * count;
  89565. }
  89566. // Raw pixels
  89567. else {
  89568. count *= pixel_size;
  89569. for (i = 0; i < count; ++i) {
  89570. pixel_data[localOffset + i] = data[offset++];
  89571. }
  89572. localOffset += count;
  89573. }
  89574. }
  89575. }
  89576. // RAW Pixels
  89577. else {
  89578. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  89579. }
  89580. // Load to texture
  89581. var x_start, y_start, x_step, y_step, y_end, x_end;
  89582. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  89583. default:
  89584. case TGATools._ORIGIN_UL:
  89585. x_start = 0;
  89586. x_step = 1;
  89587. x_end = header.width;
  89588. y_start = 0;
  89589. y_step = 1;
  89590. y_end = header.height;
  89591. break;
  89592. case TGATools._ORIGIN_BL:
  89593. x_start = 0;
  89594. x_step = 1;
  89595. x_end = header.width;
  89596. y_start = header.height - 1;
  89597. y_step = -1;
  89598. y_end = -1;
  89599. break;
  89600. case TGATools._ORIGIN_UR:
  89601. x_start = header.width - 1;
  89602. x_step = -1;
  89603. x_end = -1;
  89604. y_start = 0;
  89605. y_step = 1;
  89606. y_end = header.height;
  89607. break;
  89608. case TGATools._ORIGIN_BR:
  89609. x_start = header.width - 1;
  89610. x_step = -1;
  89611. x_end = -1;
  89612. y_start = header.height - 1;
  89613. y_step = -1;
  89614. y_end = -1;
  89615. break;
  89616. }
  89617. // Load the specify method
  89618. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  89619. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  89620. var engine = texture.getEngine();
  89621. engine._uploadDataToTextureDirectly(texture, imageData);
  89622. };
  89623. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89624. var image = pixel_data, colormap = palettes;
  89625. var width = header.width, height = header.height;
  89626. var color, i = 0, x, y;
  89627. var imageData = new Uint8Array(width * height * 4);
  89628. for (y = y_start; y !== y_end; y += y_step) {
  89629. for (x = x_start; x !== x_end; x += x_step, i++) {
  89630. color = image[i];
  89631. imageData[(x + width * y) * 4 + 3] = 255;
  89632. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  89633. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  89634. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  89635. }
  89636. }
  89637. return imageData;
  89638. };
  89639. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89640. var image = pixel_data;
  89641. var width = header.width, height = header.height;
  89642. var color, i = 0, x, y;
  89643. var imageData = new Uint8Array(width * height * 4);
  89644. for (y = y_start; y !== y_end; y += y_step) {
  89645. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89646. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  89647. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  89648. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  89649. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  89650. imageData[(x + width * y) * 4 + 0] = r;
  89651. imageData[(x + width * y) * 4 + 1] = g;
  89652. imageData[(x + width * y) * 4 + 2] = b;
  89653. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  89654. }
  89655. }
  89656. return imageData;
  89657. };
  89658. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89659. var image = pixel_data;
  89660. var width = header.width, height = header.height;
  89661. var i = 0, x, y;
  89662. var imageData = new Uint8Array(width * height * 4);
  89663. for (y = y_start; y !== y_end; y += y_step) {
  89664. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  89665. imageData[(x + width * y) * 4 + 3] = 255;
  89666. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89667. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89668. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89669. }
  89670. }
  89671. return imageData;
  89672. };
  89673. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89674. var image = pixel_data;
  89675. var width = header.width, height = header.height;
  89676. var i = 0, x, y;
  89677. var imageData = new Uint8Array(width * height * 4);
  89678. for (y = y_start; y !== y_end; y += y_step) {
  89679. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  89680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89681. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89682. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89683. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  89684. }
  89685. }
  89686. return imageData;
  89687. };
  89688. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89689. var image = pixel_data;
  89690. var width = header.width, height = header.height;
  89691. var color, i = 0, x, y;
  89692. var imageData = new Uint8Array(width * height * 4);
  89693. for (y = y_start; y !== y_end; y += y_step) {
  89694. for (x = x_start; x !== x_end; x += x_step, i++) {
  89695. color = image[i];
  89696. imageData[(x + width * y) * 4 + 0] = color;
  89697. imageData[(x + width * y) * 4 + 1] = color;
  89698. imageData[(x + width * y) * 4 + 2] = color;
  89699. imageData[(x + width * y) * 4 + 3] = 255;
  89700. }
  89701. }
  89702. return imageData;
  89703. };
  89704. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89705. var image = pixel_data;
  89706. var width = header.width, height = header.height;
  89707. var i = 0, x, y;
  89708. var imageData = new Uint8Array(width * height * 4);
  89709. for (y = y_start; y !== y_end; y += y_step) {
  89710. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89711. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  89712. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  89713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89714. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  89715. }
  89716. }
  89717. return imageData;
  89718. };
  89719. //private static _TYPE_NO_DATA = 0;
  89720. TGATools._TYPE_INDEXED = 1;
  89721. TGATools._TYPE_RGB = 2;
  89722. TGATools._TYPE_GREY = 3;
  89723. TGATools._TYPE_RLE_INDEXED = 9;
  89724. TGATools._TYPE_RLE_RGB = 10;
  89725. TGATools._TYPE_RLE_GREY = 11;
  89726. TGATools._ORIGIN_MASK = 0x30;
  89727. TGATools._ORIGIN_SHIFT = 0x04;
  89728. TGATools._ORIGIN_BL = 0x00;
  89729. TGATools._ORIGIN_BR = 0x01;
  89730. TGATools._ORIGIN_UL = 0x02;
  89731. TGATools._ORIGIN_UR = 0x03;
  89732. return TGATools;
  89733. }());
  89734. BABYLON.TGATools = TGATools;
  89735. })(BABYLON || (BABYLON = {}));
  89736. //# sourceMappingURL=babylon.tga.js.map
  89737. var BABYLON;
  89738. (function (BABYLON) {
  89739. /**
  89740. * Implementation of the TGA Texture Loader.
  89741. */
  89742. var TGATextureLoader = /** @class */ (function () {
  89743. function TGATextureLoader() {
  89744. /**
  89745. * Defines wether the loader supports cascade loading the different faces.
  89746. */
  89747. this.supportCascades = false;
  89748. }
  89749. /**
  89750. * This returns if the loader support the current file information.
  89751. * @param extension defines the file extension of the file being loaded
  89752. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89753. * @param fallback defines the fallback internal texture if any
  89754. * @param isBase64 defines whether the texture is encoded as a base64
  89755. * @param isBuffer defines whether the texture data are stored as a buffer
  89756. * @returns true if the loader can load the specified file
  89757. */
  89758. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89759. return extension.indexOf(".tga") === 0;
  89760. };
  89761. /**
  89762. * Transform the url before loading if required.
  89763. * @param rootUrl the url of the texture
  89764. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89765. * @returns the transformed texture
  89766. */
  89767. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89768. return rootUrl;
  89769. };
  89770. /**
  89771. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89772. * @param rootUrl the url of the texture
  89773. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89774. * @returns the fallback texture
  89775. */
  89776. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89777. return null;
  89778. };
  89779. /**
  89780. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89781. * @param data contains the texture data
  89782. * @param texture defines the BabylonJS internal texture
  89783. * @param createPolynomials will be true if polynomials have been requested
  89784. * @param onLoad defines the callback to trigger once the texture is ready
  89785. * @param onError defines the callback to trigger in case of error
  89786. */
  89787. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89788. throw ".env not supported in Cube.";
  89789. };
  89790. /**
  89791. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89792. * @param data contains the texture data
  89793. * @param texture defines the BabylonJS internal texture
  89794. * @param callback defines the method to call once ready to upload
  89795. */
  89796. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  89797. var uintData = new Uint8Array(data);
  89798. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  89799. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  89800. BABYLON.TGATools.UploadContent(texture, uintData);
  89801. });
  89802. };
  89803. return TGATextureLoader;
  89804. }());
  89805. // Register the loader.
  89806. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  89807. })(BABYLON || (BABYLON = {}));
  89808. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  89809. var BABYLON;
  89810. (function (BABYLON) {
  89811. /**
  89812. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  89813. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  89814. */
  89815. var KhronosTextureContainer = /** @class */ (function () {
  89816. /**
  89817. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  89818. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  89819. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  89820. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  89821. */
  89822. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  89823. this.arrayBuffer = arrayBuffer;
  89824. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  89825. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  89826. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  89827. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  89828. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  89829. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  89830. BABYLON.Tools.Error("texture missing KTX identifier");
  89831. return;
  89832. }
  89833. // load the reset of the header in native 32 bit int
  89834. var header = new Int32Array(this.arrayBuffer, 12, 13);
  89835. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  89836. var oppositeEndianess = header[0] === 0x01020304;
  89837. // read all the header elements in order they exist in the file, without modification (sans endainness)
  89838. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  89839. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  89840. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  89841. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  89842. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  89843. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  89844. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  89845. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  89846. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  89847. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  89848. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  89849. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  89850. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  89851. if (this.glType !== 0) {
  89852. BABYLON.Tools.Error("only compressed formats currently supported");
  89853. return;
  89854. }
  89855. else {
  89856. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  89857. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  89858. }
  89859. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  89860. BABYLON.Tools.Error("only 2D textures currently supported");
  89861. return;
  89862. }
  89863. if (this.numberOfArrayElements !== 0) {
  89864. BABYLON.Tools.Error("texture arrays not currently supported");
  89865. return;
  89866. }
  89867. if (this.numberOfFaces !== facesExpected) {
  89868. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  89869. return;
  89870. }
  89871. // we now have a completely validated file, so could use existence of loadType as success
  89872. // would need to make this more elaborate & adjust checks above to support more than one load type
  89873. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  89874. }
  89875. // not as fast hardware based, but will probably never need to use
  89876. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  89877. return ((val & 0xFF) << 24)
  89878. | ((val & 0xFF00) << 8)
  89879. | ((val >> 8) & 0xFF00)
  89880. | ((val >> 24) & 0xFF);
  89881. };
  89882. /**
  89883. * Uploads KTX content to a Babylon Texture.
  89884. * It is assumed that the texture has already been created & is currently bound
  89885. * @hidden
  89886. */
  89887. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  89888. switch (this.loadType) {
  89889. case KhronosTextureContainer.COMPRESSED_2D:
  89890. this._upload2DCompressedLevels(texture, loadMipmaps);
  89891. break;
  89892. case KhronosTextureContainer.TEX_2D:
  89893. case KhronosTextureContainer.COMPRESSED_3D:
  89894. case KhronosTextureContainer.TEX_3D:
  89895. }
  89896. };
  89897. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  89898. // initialize width & height for level 1
  89899. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  89900. var width = this.pixelWidth;
  89901. var height = this.pixelHeight;
  89902. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  89903. for (var level = 0; level < mipmapCount; level++) {
  89904. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  89905. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  89906. for (var face = 0; face < this.numberOfFaces; face++) {
  89907. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  89908. var engine = texture.getEngine();
  89909. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  89910. dataOffset += imageSize; // add size of the image for the next face/mipmap
  89911. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  89912. }
  89913. width = Math.max(1.0, width * 0.5);
  89914. height = Math.max(1.0, height * 0.5);
  89915. }
  89916. };
  89917. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  89918. // load types
  89919. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  89920. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  89921. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  89922. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  89923. return KhronosTextureContainer;
  89924. }());
  89925. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  89926. })(BABYLON || (BABYLON = {}));
  89927. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  89928. var BABYLON;
  89929. (function (BABYLON) {
  89930. /**
  89931. * Implementation of the KTX Texture Loader.
  89932. */
  89933. var KTXTextureLoader = /** @class */ (function () {
  89934. function KTXTextureLoader() {
  89935. /**
  89936. * Defines wether the loader supports cascade loading the different faces.
  89937. */
  89938. this.supportCascades = false;
  89939. }
  89940. /**
  89941. * This returns if the loader support the current file information.
  89942. * @param extension defines the file extension of the file being loaded
  89943. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89944. * @param fallback defines the fallback internal texture if any
  89945. * @param isBase64 defines whether the texture is encoded as a base64
  89946. * @param isBuffer defines whether the texture data are stored as a buffer
  89947. * @returns true if the loader can load the specified file
  89948. */
  89949. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89950. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  89951. return true;
  89952. }
  89953. return false;
  89954. };
  89955. /**
  89956. * Transform the url before loading if required.
  89957. * @param rootUrl the url of the texture
  89958. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89959. * @returns the transformed texture
  89960. */
  89961. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89962. var lastDot = rootUrl.lastIndexOf('.');
  89963. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  89964. };
  89965. /**
  89966. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89967. * @param rootUrl the url of the texture
  89968. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89969. * @returns the fallback texture
  89970. */
  89971. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89972. // remove the format appended to the rootUrl in the original createCubeTexture call.
  89973. var exp = new RegExp("" + textureFormatInUse + "$");
  89974. return rootUrl.replace(exp, "");
  89975. };
  89976. /**
  89977. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89978. * @param data contains the texture data
  89979. * @param texture defines the BabylonJS internal texture
  89980. * @param createPolynomials will be true if polynomials have been requested
  89981. * @param onLoad defines the callback to trigger once the texture is ready
  89982. * @param onError defines the callback to trigger in case of error
  89983. */
  89984. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89985. if (Array.isArray(data)) {
  89986. return;
  89987. }
  89988. var engine = texture.getEngine();
  89989. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  89990. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  89991. engine._unpackFlipY(true);
  89992. ktx.uploadLevels(texture, texture.generateMipMaps);
  89993. texture.width = ktx.pixelWidth;
  89994. texture.height = ktx.pixelHeight;
  89995. engine._setCubeMapTextureParams(loadMipmap);
  89996. texture.isReady = true;
  89997. };
  89998. /**
  89999. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90000. * @param data contains the texture data
  90001. * @param texture defines the BabylonJS internal texture
  90002. * @param callback defines the method to call once ready to upload
  90003. */
  90004. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90005. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90006. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90007. ktx.uploadLevels(texture, texture.generateMipMaps);
  90008. });
  90009. };
  90010. return KTXTextureLoader;
  90011. }());
  90012. // Register the loader.
  90013. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90014. })(BABYLON || (BABYLON = {}));
  90015. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90016. var BABYLON;
  90017. (function (BABYLON) {
  90018. /**
  90019. * Sets of helpers addressing the serialization and deserialization of environment texture
  90020. * stored in a BabylonJS env file.
  90021. * Those files are usually stored as .env files.
  90022. */
  90023. var EnvironmentTextureTools = /** @class */ (function () {
  90024. function EnvironmentTextureTools() {
  90025. }
  90026. /**
  90027. * Gets the environment info from an env file.
  90028. * @param data The array buffer containing the .env bytes.
  90029. * @returns the environment file info (the json header) if successfully parsed.
  90030. */
  90031. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90032. var dataView = new DataView(data);
  90033. var pos = 0;
  90034. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90035. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90036. BABYLON.Tools.Error('Not a babylon environment map');
  90037. return null;
  90038. }
  90039. }
  90040. // Read json manifest - collect characters up to null terminator
  90041. var manifestString = '';
  90042. var charCode = 0x00;
  90043. while ((charCode = dataView.getUint8(pos++))) {
  90044. manifestString += String.fromCharCode(charCode);
  90045. }
  90046. var manifest = JSON.parse(manifestString);
  90047. if (manifest.specular) {
  90048. // Extend the header with the position of the payload.
  90049. manifest.specular.specularDataPosition = pos;
  90050. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90051. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90052. }
  90053. return manifest;
  90054. };
  90055. /**
  90056. * Creates an environment texture from a loaded cube texture.
  90057. * @param texture defines the cube texture to convert in env file
  90058. * @return a promise containing the environment data if succesfull.
  90059. */
  90060. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90061. var _this = this;
  90062. var internalTexture = texture.getInternalTexture();
  90063. if (!internalTexture) {
  90064. return Promise.reject("The cube texture is invalid.");
  90065. }
  90066. if (!texture._prefiltered) {
  90067. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90068. }
  90069. var engine = internalTexture.getEngine();
  90070. if (engine && engine.premultipliedAlpha) {
  90071. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90072. }
  90073. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90074. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90075. }
  90076. var canvas = engine.getRenderingCanvas();
  90077. if (!canvas) {
  90078. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  90079. }
  90080. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90081. if (!engine.getCaps().textureFloatRender) {
  90082. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90083. if (!engine.getCaps().textureHalfFloatRender) {
  90084. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  90085. }
  90086. }
  90087. var cubeWidth = internalTexture.width;
  90088. var hostingScene = new BABYLON.Scene(engine);
  90089. var specularTextures = {};
  90090. var promises = [];
  90091. // Read and collect all mipmaps data from the cube.
  90092. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  90093. mipmapsCount = Math.round(mipmapsCount);
  90094. var _loop_1 = function (i) {
  90095. var faceWidth = Math.pow(2, mipmapsCount - i);
  90096. var _loop_2 = function (face) {
  90097. var data = texture.readPixels(face, i);
  90098. // Creates a temp texture with the face data.
  90099. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  90100. // And rgbdEncode them.
  90101. var promise = new Promise(function (resolve, reject) {
  90102. 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);
  90103. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90104. rgbdPostProcess.onApply = function (effect) {
  90105. effect._bindTexture("textureSampler", tempTexture);
  90106. };
  90107. // As the process needs to happen on the main canvas, keep track of the current size
  90108. var currentW = engine.getRenderWidth();
  90109. var currentH = engine.getRenderHeight();
  90110. // Set the desired size for the texture
  90111. engine.setSize(faceWidth, faceWidth);
  90112. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  90113. // Reading datas from WebGL
  90114. BABYLON.Tools.ToBlob(canvas, function (blob) {
  90115. var fileReader = new FileReader();
  90116. fileReader.onload = function (event) {
  90117. var arrayBuffer = event.target.result;
  90118. specularTextures[i * 6 + face] = arrayBuffer;
  90119. resolve();
  90120. };
  90121. fileReader.readAsArrayBuffer(blob);
  90122. });
  90123. // Reapply the previous canvas size
  90124. engine.setSize(currentW, currentH);
  90125. });
  90126. });
  90127. promises.push(promise);
  90128. };
  90129. // All faces of the cube.
  90130. for (var face = 0; face < 6; face++) {
  90131. _loop_2(face);
  90132. }
  90133. };
  90134. for (var i = 0; i <= mipmapsCount; i++) {
  90135. _loop_1(i);
  90136. }
  90137. // Once all the textures haves been collected as RGBD stored in PNGs
  90138. return Promise.all(promises).then(function () {
  90139. // We can delete the hosting scene keeping track of all the creation objects
  90140. hostingScene.dispose();
  90141. // Creates the json header for the env texture
  90142. var info = {
  90143. version: 1,
  90144. width: cubeWidth,
  90145. irradiance: _this._CreateEnvTextureIrradiance(texture),
  90146. specular: {
  90147. mipmaps: [],
  90148. lodGenerationScale: texture.lodGenerationScale
  90149. }
  90150. };
  90151. // Sets the specular image data information
  90152. var position = 0;
  90153. for (var i = 0; i <= mipmapsCount; i++) {
  90154. for (var face = 0; face < 6; face++) {
  90155. var byteLength = specularTextures[i * 6 + face].byteLength;
  90156. info.specular.mipmaps.push({
  90157. length: byteLength,
  90158. position: position
  90159. });
  90160. position += byteLength;
  90161. }
  90162. }
  90163. // Encode the JSON as an array buffer
  90164. var infoString = JSON.stringify(info);
  90165. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  90166. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  90167. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  90168. infoView[i] = infoString.charCodeAt(i);
  90169. }
  90170. // Ends up with a null terminator for easier parsing
  90171. infoView[infoString.length] = 0x00;
  90172. // Computes the final required size and creates the storage
  90173. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  90174. var finalBuffer = new ArrayBuffer(totalSize);
  90175. var finalBufferView = new Uint8Array(finalBuffer);
  90176. var dataView = new DataView(finalBuffer);
  90177. // Copy the magic bytes identifying the file in
  90178. var pos = 0;
  90179. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90180. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  90181. }
  90182. // Add the json info
  90183. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  90184. pos += infoBuffer.byteLength;
  90185. // Finally inserts the texture data
  90186. for (var i = 0; i <= mipmapsCount; i++) {
  90187. for (var face = 0; face < 6; face++) {
  90188. var dataBuffer = specularTextures[i * 6 + face];
  90189. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  90190. pos += dataBuffer.byteLength;
  90191. }
  90192. }
  90193. // Voila
  90194. return finalBuffer;
  90195. });
  90196. };
  90197. /**
  90198. * Creates a JSON representation of the spherical data.
  90199. * @param texture defines the texture containing the polynomials
  90200. * @return the JSON representation of the spherical info
  90201. */
  90202. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  90203. var polynmials = texture.sphericalPolynomial;
  90204. if (polynmials == null) {
  90205. return null;
  90206. }
  90207. return {
  90208. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  90209. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  90210. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  90211. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  90212. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  90213. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  90214. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  90215. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  90216. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  90217. };
  90218. };
  90219. /**
  90220. * Uploads the texture info contained in the env file to the GPU.
  90221. * @param texture defines the internal texture to upload to
  90222. * @param arrayBuffer defines the buffer cotaining the data to load
  90223. * @param info defines the texture info retrieved through the GetEnvInfo method
  90224. * @returns a promise
  90225. */
  90226. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  90227. if (info.version !== 1) {
  90228. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  90229. }
  90230. var specularInfo = info.specular;
  90231. if (!specularInfo) {
  90232. // Nothing else parsed so far
  90233. return Promise.resolve();
  90234. }
  90235. // Double checks the enclosed info
  90236. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  90237. mipmapsCount = Math.round(mipmapsCount) + 1;
  90238. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  90239. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  90240. }
  90241. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  90242. var imageData = new Array(mipmapsCount);
  90243. for (var i = 0; i < mipmapsCount; i++) {
  90244. imageData[i] = new Array(6);
  90245. for (var face = 0; face < 6; face++) {
  90246. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90247. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90248. }
  90249. }
  90250. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90251. };
  90252. /**
  90253. * Uploads the levels of image data to the GPU.
  90254. * @param texture defines the internal texture to upload to
  90255. * @param imageData defines the array buffer views of image data [mipmap][face]
  90256. * @returns a promise
  90257. */
  90258. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90259. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90260. throw new Error("Texture size must be a power of two");
  90261. }
  90262. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90263. // Gets everything ready.
  90264. var engine = texture.getEngine();
  90265. var expandTexture = false;
  90266. var generateNonLODTextures = false;
  90267. var rgbdPostProcess = null;
  90268. var cubeRtt = null;
  90269. var lodTextures = null;
  90270. var caps = engine.getCaps();
  90271. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90272. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90273. texture.generateMipMaps = true;
  90274. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90275. // Add extra process if texture lod is not supported
  90276. if (!caps.textureLOD) {
  90277. expandTexture = false;
  90278. generateNonLODTextures = true;
  90279. lodTextures = {};
  90280. }
  90281. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90282. else if (engine.webGLVersion < 2) {
  90283. expandTexture = false;
  90284. }
  90285. // If half float available we can uncompress the texture
  90286. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90287. expandTexture = true;
  90288. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90289. }
  90290. // If full float available we can uncompress the texture
  90291. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90292. expandTexture = true;
  90293. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90294. }
  90295. // Expand the texture if possible
  90296. if (expandTexture) {
  90297. // Simply run through the decode PP
  90298. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90299. texture._isRGBD = false;
  90300. texture.invertY = false;
  90301. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90302. generateDepthBuffer: false,
  90303. generateMipMaps: true,
  90304. generateStencilBuffer: false,
  90305. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90306. type: texture.type,
  90307. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90308. });
  90309. }
  90310. else {
  90311. texture._isRGBD = true;
  90312. texture.invertY = true;
  90313. // In case of missing support, applies the same patch than DDS files.
  90314. if (generateNonLODTextures) {
  90315. var mipSlices = 3;
  90316. var scale = texture._lodGenerationScale;
  90317. var offset = texture._lodGenerationOffset;
  90318. for (var i = 0; i < mipSlices; i++) {
  90319. //compute LOD from even spacing in smoothness (matching shader calculation)
  90320. var smoothness = i / (mipSlices - 1);
  90321. var roughness = 1 - smoothness;
  90322. var minLODIndex = offset; // roughness = 0
  90323. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90324. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90325. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90326. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90327. glTextureFromLod.isCube = true;
  90328. glTextureFromLod.invertY = true;
  90329. glTextureFromLod.generateMipMaps = false;
  90330. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90331. // Wrap in a base texture for easy binding.
  90332. var lodTexture = new BABYLON.BaseTexture(null);
  90333. lodTexture.isCube = true;
  90334. lodTexture._texture = glTextureFromLod;
  90335. lodTextures[mipmapIndex] = lodTexture;
  90336. switch (i) {
  90337. case 0:
  90338. texture._lodTextureLow = lodTexture;
  90339. break;
  90340. case 1:
  90341. texture._lodTextureMid = lodTexture;
  90342. break;
  90343. case 2:
  90344. texture._lodTextureHigh = lodTexture;
  90345. break;
  90346. }
  90347. }
  90348. }
  90349. }
  90350. var promises = [];
  90351. var _loop_3 = function (i) {
  90352. var _loop_4 = function (face) {
  90353. // Constructs an image element from image data
  90354. var bytes = imageData[i][face];
  90355. var blob = new Blob([bytes], { type: 'image/png' });
  90356. var url = URL.createObjectURL(blob);
  90357. var image = new Image();
  90358. image.src = url;
  90359. // Enqueue promise to upload to the texture.
  90360. var promise = new Promise(function (resolve, reject) {
  90361. image.onload = function () {
  90362. if (expandTexture) {
  90363. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90364. reject(message);
  90365. }, image);
  90366. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90367. // Uncompress the data to a RTT
  90368. rgbdPostProcess.onApply = function (effect) {
  90369. effect._bindTexture("textureSampler", tempTexture_1);
  90370. effect.setFloat2("scale", 1, 1);
  90371. };
  90372. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90373. // Cleanup
  90374. engine.restoreDefaultFramebuffer();
  90375. tempTexture_1.dispose();
  90376. window.URL.revokeObjectURL(url);
  90377. resolve();
  90378. });
  90379. }
  90380. else {
  90381. engine._uploadImageToTexture(texture, image, face, i);
  90382. // Upload the face to the non lod texture support
  90383. if (generateNonLODTextures) {
  90384. var lodTexture = lodTextures[i];
  90385. if (lodTexture) {
  90386. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90387. }
  90388. }
  90389. resolve();
  90390. }
  90391. };
  90392. image.onerror = function (error) {
  90393. reject(error);
  90394. };
  90395. });
  90396. promises.push(promise);
  90397. };
  90398. // All faces
  90399. for (var face = 0; face < 6; face++) {
  90400. _loop_4(face);
  90401. }
  90402. };
  90403. // All mipmaps up to provided number of images
  90404. for (var i = 0; i < imageData.length; i++) {
  90405. _loop_3(i);
  90406. }
  90407. // Fill remaining mipmaps with black textures.
  90408. if (imageData.length < mipmapsCount) {
  90409. var data = void 0;
  90410. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90411. var dataLength = size * size * 4;
  90412. switch (texture.type) {
  90413. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90414. data = new Uint8Array(dataLength);
  90415. break;
  90416. }
  90417. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90418. data = new Uint16Array(dataLength);
  90419. break;
  90420. }
  90421. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90422. data = new Float32Array(dataLength);
  90423. break;
  90424. }
  90425. }
  90426. for (var i = imageData.length; i < mipmapsCount; i++) {
  90427. for (var face = 0; face < 6; face++) {
  90428. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90429. }
  90430. }
  90431. }
  90432. // Once all done, finishes the cleanup and return
  90433. return Promise.all(promises).then(function () {
  90434. // Release temp RTT.
  90435. if (cubeRtt) {
  90436. engine._releaseFramebufferObjects(cubeRtt);
  90437. cubeRtt._swapAndDie(texture);
  90438. }
  90439. // Release temp Post Process.
  90440. if (rgbdPostProcess) {
  90441. rgbdPostProcess.dispose();
  90442. }
  90443. // Flag internal texture as ready in case they are in use.
  90444. if (generateNonLODTextures) {
  90445. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90446. texture._lodTextureHigh._texture.isReady = true;
  90447. }
  90448. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90449. texture._lodTextureMid._texture.isReady = true;
  90450. }
  90451. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90452. texture._lodTextureLow._texture.isReady = true;
  90453. }
  90454. }
  90455. });
  90456. };
  90457. /**
  90458. * Uploads spherical polynomials information to the texture.
  90459. * @param texture defines the texture we are trying to upload the information to
  90460. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90461. */
  90462. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90463. if (info.version !== 1) {
  90464. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90465. }
  90466. var irradianceInfo = info.irradiance;
  90467. if (!irradianceInfo) {
  90468. return;
  90469. }
  90470. var sp = new BABYLON.SphericalPolynomial();
  90471. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90472. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90473. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90474. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90475. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90476. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90477. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90478. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90479. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90480. texture._sphericalPolynomial = sp;
  90481. };
  90482. /**
  90483. * Magic number identifying the env file.
  90484. */
  90485. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90486. return EnvironmentTextureTools;
  90487. }());
  90488. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90489. })(BABYLON || (BABYLON = {}));
  90490. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90491. var BABYLON;
  90492. (function (BABYLON) {
  90493. /**
  90494. * Implementation of the ENV Texture Loader.
  90495. */
  90496. var ENVTextureLoader = /** @class */ (function () {
  90497. function ENVTextureLoader() {
  90498. /**
  90499. * Defines wether the loader supports cascade loading the different faces.
  90500. */
  90501. this.supportCascades = false;
  90502. }
  90503. /**
  90504. * This returns if the loader support the current file information.
  90505. * @param extension defines the file extension of the file being loaded
  90506. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90507. * @param fallback defines the fallback internal texture if any
  90508. * @param isBase64 defines whether the texture is encoded as a base64
  90509. * @param isBuffer defines whether the texture data are stored as a buffer
  90510. * @returns true if the loader can load the specified file
  90511. */
  90512. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90513. return extension.indexOf(".env") === 0;
  90514. };
  90515. /**
  90516. * Transform the url before loading if required.
  90517. * @param rootUrl the url of the texture
  90518. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90519. * @returns the transformed texture
  90520. */
  90521. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90522. return rootUrl;
  90523. };
  90524. /**
  90525. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90526. * @param rootUrl the url of the texture
  90527. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90528. * @returns the fallback texture
  90529. */
  90530. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90531. return null;
  90532. };
  90533. /**
  90534. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90535. * @param data contains the texture data
  90536. * @param texture defines the BabylonJS internal texture
  90537. * @param createPolynomials will be true if polynomials have been requested
  90538. * @param onLoad defines the callback to trigger once the texture is ready
  90539. * @param onError defines the callback to trigger in case of error
  90540. */
  90541. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90542. if (Array.isArray(data)) {
  90543. return;
  90544. }
  90545. data = data;
  90546. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  90547. if (info) {
  90548. texture.width = info.width;
  90549. texture.height = info.width;
  90550. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  90551. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  90552. texture.isReady = true;
  90553. if (onLoad) {
  90554. onLoad();
  90555. }
  90556. });
  90557. }
  90558. else if (onError) {
  90559. onError("Can not parse the environment file", null);
  90560. }
  90561. };
  90562. /**
  90563. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90564. * @param data contains the texture data
  90565. * @param texture defines the BabylonJS internal texture
  90566. * @param callback defines the method to call once ready to upload
  90567. */
  90568. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  90569. throw ".env not supported in 2d.";
  90570. };
  90571. return ENVTextureLoader;
  90572. }());
  90573. // Register the loader.
  90574. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  90575. })(BABYLON || (BABYLON = {}));
  90576. //# sourceMappingURL=babylon.envTextureLoader.js.map
  90577. var BABYLON;
  90578. (function (BABYLON) {
  90579. /**
  90580. * Renders a layer on top of an existing scene
  90581. */
  90582. var UtilityLayerRenderer = /** @class */ (function () {
  90583. /**
  90584. * Instantiates a UtilityLayerRenderer
  90585. * @param originalScene the original scene that will be rendered on top of
  90586. */
  90587. function UtilityLayerRenderer(
  90588. /** the original scene that will be rendered on top of */
  90589. originalScene) {
  90590. var _this = this;
  90591. this.originalScene = originalScene;
  90592. this._pointerCaptures = {};
  90593. this._lastPointerEvents = {};
  90594. /**
  90595. * If the utility layer should automatically be rendered on top of existing scene
  90596. */
  90597. this.shouldRender = true;
  90598. /**
  90599. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  90600. */
  90601. this.onlyCheckPointerDownEvents = true;
  90602. /**
  90603. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  90604. */
  90605. this.processAllEvents = false;
  90606. /**
  90607. * Observable raised when the pointer move from the utility layer scene to the main scene
  90608. */
  90609. this.onPointerOutObservable = new BABYLON.Observable();
  90610. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  90611. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  90612. this.utilityLayerScene._allowPostProcessClear = false;
  90613. originalScene.getEngine().scenes.pop();
  90614. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  90615. this.utilityLayerScene.detachControl();
  90616. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  90617. if (!_this.processAllEvents) {
  90618. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  90619. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  90620. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  90621. return;
  90622. }
  90623. }
  90624. var pointerEvent = (prePointerInfo.event);
  90625. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  90626. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90627. return;
  90628. }
  90629. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  90630. if (!prePointerInfo.ray && utilityScenePick) {
  90631. prePointerInfo.ray = utilityScenePick.ray;
  90632. }
  90633. // always fire the prepointer oversvable
  90634. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  90635. // allow every non pointer down event to flow to the utility layer
  90636. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  90637. if (!prePointerInfo.skipOnPointerObservable) {
  90638. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90639. }
  90640. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  90641. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90642. }
  90643. return;
  90644. }
  90645. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  90646. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  90647. if (utilityScenePick && utilityScenePick.hit) {
  90648. if (!prePointerInfo.skipOnPointerObservable) {
  90649. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90650. }
  90651. prePointerInfo.skipOnPointerObservable = true;
  90652. }
  90653. }
  90654. else {
  90655. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  90656. var pointerEvent_1 = (prePointerInfo.event);
  90657. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  90658. if (originalScenePick && utilityScenePick) {
  90659. // No pick in utility scene
  90660. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  90661. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90662. // We touched an utility mesh present in the main scene
  90663. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90664. prePointerInfo.skipOnPointerObservable = true;
  90665. }
  90666. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90667. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  90668. }
  90669. }
  90670. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  90671. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  90672. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  90673. // If a previous utility layer set this, do not unset this
  90674. if (!prePointerInfo.skipOnPointerObservable) {
  90675. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  90676. }
  90677. }
  90678. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  90679. // We have a pick in both scenes but main is closer than utility
  90680. // We touched an utility mesh present in the main scene
  90681. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90682. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90683. prePointerInfo.skipOnPointerObservable = true;
  90684. }
  90685. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  90686. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  90687. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  90688. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  90689. }
  90690. }
  90691. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  90692. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  90693. }
  90694. }
  90695. }
  90696. });
  90697. // Render directly on top of existing scene without clearing
  90698. this.utilityLayerScene.autoClear = false;
  90699. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  90700. if (_this.shouldRender) {
  90701. _this.render();
  90702. }
  90703. });
  90704. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  90705. _this.dispose();
  90706. });
  90707. this._updateCamera();
  90708. }
  90709. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  90710. /**
  90711. * 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)
  90712. */
  90713. get: function () {
  90714. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  90715. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90716. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90717. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90718. });
  90719. }
  90720. return UtilityLayerRenderer._DefaultUtilityLayer;
  90721. },
  90722. enumerable: true,
  90723. configurable: true
  90724. });
  90725. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  90726. /**
  90727. * 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)
  90728. */
  90729. get: function () {
  90730. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  90731. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90732. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90733. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90734. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90735. });
  90736. }
  90737. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  90738. },
  90739. enumerable: true,
  90740. configurable: true
  90741. });
  90742. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  90743. if (!prePointerInfo.skipOnPointerObservable) {
  90744. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  90745. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  90746. }
  90747. };
  90748. /**
  90749. * Renders the utility layers scene on top of the original scene
  90750. */
  90751. UtilityLayerRenderer.prototype.render = function () {
  90752. this._updateCamera();
  90753. if (this.utilityLayerScene.activeCamera) {
  90754. // Set the camera's scene to utility layers scene
  90755. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  90756. var camera = this.utilityLayerScene.activeCamera;
  90757. camera._scene = this.utilityLayerScene;
  90758. if (camera.leftCamera) {
  90759. camera.leftCamera._scene = this.utilityLayerScene;
  90760. }
  90761. if (camera.rightCamera) {
  90762. camera.rightCamera._scene = this.utilityLayerScene;
  90763. }
  90764. this.utilityLayerScene.render(false);
  90765. // Reset camera's scene back to original
  90766. camera._scene = oldScene;
  90767. if (camera.leftCamera) {
  90768. camera.leftCamera._scene = oldScene;
  90769. }
  90770. if (camera.rightCamera) {
  90771. camera.rightCamera._scene = oldScene;
  90772. }
  90773. }
  90774. };
  90775. /**
  90776. * Disposes of the renderer
  90777. */
  90778. UtilityLayerRenderer.prototype.dispose = function () {
  90779. this.onPointerOutObservable.clear();
  90780. if (this._afterRenderObserver) {
  90781. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  90782. }
  90783. if (this._sceneDisposeObserver) {
  90784. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90785. }
  90786. if (this._originalPointerObserver) {
  90787. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  90788. }
  90789. this.utilityLayerScene.dispose();
  90790. };
  90791. UtilityLayerRenderer.prototype._updateCamera = function () {
  90792. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  90793. };
  90794. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90795. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90796. return UtilityLayerRenderer;
  90797. }());
  90798. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  90799. })(BABYLON || (BABYLON = {}));
  90800. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  90801. //# sourceMappingURL=babylon.behavior.js.map
  90802. var BABYLON;
  90803. (function (BABYLON) {
  90804. /**
  90805. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  90806. */
  90807. var PointerDragBehavior = /** @class */ (function () {
  90808. /**
  90809. * Creates a pointer drag behavior that can be attached to a mesh
  90810. * @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)
  90811. */
  90812. function PointerDragBehavior(options) {
  90813. /**
  90814. * 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)
  90815. */
  90816. this.maxDragAngle = 0;
  90817. /**
  90818. * @hidden
  90819. */
  90820. this._useAlternatePickedPointAboveMaxDragAngle = false;
  90821. /**
  90822. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90823. */
  90824. this.currentDraggingPointerID = -1;
  90825. /**
  90826. * If the behavior is currently in a dragging state
  90827. */
  90828. this.dragging = false;
  90829. /**
  90830. * 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)
  90831. */
  90832. this.dragDeltaRatio = 0.2;
  90833. /**
  90834. * If the drag plane orientation should be updated during the dragging (Default: true)
  90835. */
  90836. this.updateDragPlane = true;
  90837. // Debug mode will display drag planes to help visualize behavior
  90838. this._debugMode = false;
  90839. this._moving = false;
  90840. /**
  90841. * Fires each time the attached mesh is dragged with the pointer
  90842. * * delta between last drag position and current drag position in world space
  90843. * * dragDistance along the drag axis
  90844. * * dragPlaneNormal normal of the current drag plane used during the drag
  90845. * * dragPlanePoint in world space where the drag intersects the drag plane
  90846. */
  90847. this.onDragObservable = new BABYLON.Observable();
  90848. /**
  90849. * Fires each time a drag begins (eg. mouse down on mesh)
  90850. */
  90851. this.onDragStartObservable = new BABYLON.Observable();
  90852. /**
  90853. * Fires each time a drag ends (eg. mouse release after drag)
  90854. */
  90855. this.onDragEndObservable = new BABYLON.Observable();
  90856. /**
  90857. * If the attached mesh should be moved when dragged
  90858. */
  90859. this.moveAttached = true;
  90860. /**
  90861. * If the drag behavior will react to drag events (Default: true)
  90862. */
  90863. this.enabled = true;
  90864. /**
  90865. * If camera controls should be detached during the drag
  90866. */
  90867. this.detachCameraControls = true;
  90868. /**
  90869. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  90870. */
  90871. this.useObjectOrienationForDragging = true;
  90872. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90873. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  90874. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  90875. // Variables to avoid instantiation in the below method
  90876. this._pointA = new BABYLON.Vector3(0, 0, 0);
  90877. this._pointB = new BABYLON.Vector3(0, 0, 0);
  90878. this._pointC = new BABYLON.Vector3(0, 0, 0);
  90879. this._lineA = new BABYLON.Vector3(0, 0, 0);
  90880. this._lineB = new BABYLON.Vector3(0, 0, 0);
  90881. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  90882. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  90883. this._options = options ? options : {};
  90884. var optionCount = 0;
  90885. if (this._options.dragAxis) {
  90886. optionCount++;
  90887. }
  90888. if (this._options.dragPlaneNormal) {
  90889. optionCount++;
  90890. }
  90891. if (optionCount > 1) {
  90892. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  90893. }
  90894. }
  90895. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  90896. /**
  90897. * The name of the behavior
  90898. */
  90899. get: function () {
  90900. return "PointerDrag";
  90901. },
  90902. enumerable: true,
  90903. configurable: true
  90904. });
  90905. /**
  90906. * Initializes the behavior
  90907. */
  90908. PointerDragBehavior.prototype.init = function () { };
  90909. /**
  90910. * Attaches the drag behavior the passed in mesh
  90911. * @param ownerNode The mesh that will be dragged around once attached
  90912. */
  90913. PointerDragBehavior.prototype.attach = function (ownerNode) {
  90914. var _this = this;
  90915. this._scene = ownerNode.getScene();
  90916. this._attachedNode = ownerNode;
  90917. // Initialize drag plane to not interfere with existing scene
  90918. if (!PointerDragBehavior._planeScene) {
  90919. if (this._debugMode) {
  90920. PointerDragBehavior._planeScene = this._scene;
  90921. }
  90922. else {
  90923. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  90924. PointerDragBehavior._planeScene.detachControl();
  90925. this._scene.getEngine().scenes.pop();
  90926. this._scene.onDisposeObservable.addOnce(function () {
  90927. PointerDragBehavior._planeScene.dispose();
  90928. PointerDragBehavior._planeScene = null;
  90929. });
  90930. }
  90931. }
  90932. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  90933. // State of the drag
  90934. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  90935. var delta = new BABYLON.Vector3(0, 0, 0);
  90936. var dragLength = 0;
  90937. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  90938. var pickPredicate = function (m) {
  90939. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  90940. };
  90941. var attachedElement = null;
  90942. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90943. if (!_this.enabled) {
  90944. return;
  90945. }
  90946. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90947. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90948. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  90949. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90950. if (pickedPoint) {
  90951. _this.dragging = true;
  90952. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90953. _this.lastDragPosition.copyFrom(pickedPoint);
  90954. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  90955. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  90956. // Detatch camera controls
  90957. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90958. if (_this._scene.activeCamera.inputs.attachedElement) {
  90959. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90960. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90961. }
  90962. else {
  90963. attachedElement = null;
  90964. }
  90965. }
  90966. }
  90967. }
  90968. }
  90969. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90970. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90971. _this.releaseDrag();
  90972. // Reattach camera controls
  90973. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90974. _this._scene.activeCamera.attachControl(attachedElement, true);
  90975. }
  90976. }
  90977. }
  90978. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90979. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90980. _this._moving = true;
  90981. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90982. if (pickedPoint) {
  90983. if (_this.updateDragPlane) {
  90984. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  90985. }
  90986. // depending on the drag mode option drag accordingly
  90987. if (_this._options.dragAxis) {
  90988. // Convert local drag axis to world
  90989. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  90990. // Project delta drag from the drag plane onto the drag axis
  90991. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  90992. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  90993. _this._worldDragAxis.scaleToRef(dragLength, delta);
  90994. }
  90995. else {
  90996. dragLength = delta.length();
  90997. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  90998. }
  90999. targetPosition.addInPlace(delta);
  91000. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  91001. _this.lastDragPosition.copyFrom(pickedPoint);
  91002. }
  91003. }
  91004. }
  91005. });
  91006. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91007. if (_this._moving && _this.moveAttached) {
  91008. // Slowly move mesh to avoid jitter
  91009. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  91010. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91011. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91012. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  91013. }
  91014. });
  91015. };
  91016. PointerDragBehavior.prototype.releaseDrag = function () {
  91017. this.dragging = false;
  91018. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91019. this.currentDraggingPointerID = -1;
  91020. this._moving = false;
  91021. };
  91022. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91023. var _this = this;
  91024. if (!ray) {
  91025. return null;
  91026. }
  91027. // Calculate angle between plane normal and ray
  91028. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  91029. // Correct if ray is casted from oposite side
  91030. if (angle > Math.PI / 2) {
  91031. angle = Math.PI - angle;
  91032. }
  91033. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  91034. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  91035. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  91036. // Invert ray direction along the towards object axis
  91037. this._tmpVector.copyFrom(ray.direction);
  91038. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  91039. this._alternatePickedPoint.normalize();
  91040. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  91041. this._tmpVector.addInPlace(this._alternatePickedPoint);
  91042. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  91043. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  91044. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  91045. this._alternatePickedPoint.addInPlace(this._tmpVector);
  91046. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  91047. return this._alternatePickedPoint;
  91048. }
  91049. else {
  91050. return null;
  91051. }
  91052. }
  91053. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  91054. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  91055. return pickResult.pickedPoint;
  91056. }
  91057. else {
  91058. return null;
  91059. }
  91060. };
  91061. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  91062. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  91063. this._pointA.copyFrom(dragPlanePosition);
  91064. if (this._options.dragAxis) {
  91065. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  91066. // Calculate plane normal in direction of camera but perpendicular to drag axis
  91067. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  91068. ray.origin.subtractToRef(this._pointA, this._pointC);
  91069. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  91070. // Get perpendicular line from direction to camera and drag axis
  91071. this._pointB.subtractToRef(this._pointA, this._lineA);
  91072. this._pointC.subtractToRef(this._pointA, this._lineB);
  91073. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  91074. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  91075. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  91076. this._lookAt.normalize();
  91077. this._dragPlane.position.copyFrom(this._pointA);
  91078. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  91079. this._dragPlane.lookAt(this._lookAt);
  91080. }
  91081. else if (this._options.dragPlaneNormal) {
  91082. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  91083. this._dragPlane.position.copyFrom(this._pointA);
  91084. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  91085. this._dragPlane.lookAt(this._lookAt);
  91086. }
  91087. else {
  91088. this._dragPlane.position.copyFrom(this._pointA);
  91089. this._dragPlane.lookAt(ray.origin);
  91090. }
  91091. this._dragPlane.computeWorldMatrix(true);
  91092. };
  91093. /**
  91094. * Detaches the behavior from the mesh
  91095. */
  91096. PointerDragBehavior.prototype.detach = function () {
  91097. if (this._pointerObserver) {
  91098. this._scene.onPointerObservable.remove(this._pointerObserver);
  91099. }
  91100. if (this._beforeRenderObserver) {
  91101. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91102. }
  91103. };
  91104. return PointerDragBehavior;
  91105. }());
  91106. BABYLON.PointerDragBehavior = PointerDragBehavior;
  91107. })(BABYLON || (BABYLON = {}));
  91108. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  91109. var BABYLON;
  91110. (function (BABYLON) {
  91111. /**
  91112. * A behavior that when attached to a mesh will allow the mesh to be scaled
  91113. */
  91114. var MultiPointerScaleBehavior = /** @class */ (function () {
  91115. function MultiPointerScaleBehavior() {
  91116. this._startDistance = 0;
  91117. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  91118. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  91119. this._sceneRenderObserver = null;
  91120. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  91121. this._dragBehaviorA.moveAttached = false;
  91122. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  91123. this._dragBehaviorB.moveAttached = false;
  91124. }
  91125. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  91126. /**
  91127. * The name of the behavior
  91128. */
  91129. get: function () {
  91130. return "MultiPointerScale";
  91131. },
  91132. enumerable: true,
  91133. configurable: true
  91134. });
  91135. /**
  91136. * Initializes the behavior
  91137. */
  91138. MultiPointerScaleBehavior.prototype.init = function () { };
  91139. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  91140. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  91141. };
  91142. /**
  91143. * Attaches the scale behavior the passed in mesh
  91144. * @param ownerNode The mesh that will be scaled around once attached
  91145. */
  91146. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  91147. var _this = this;
  91148. this._ownerNode = ownerNode;
  91149. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  91150. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  91151. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91152. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91153. _this._dragBehaviorA.releaseDrag();
  91154. }
  91155. else {
  91156. _this._initialScale.copyFrom(ownerNode.scaling);
  91157. _this._startDistance = _this._getCurrentDistance();
  91158. }
  91159. }
  91160. });
  91161. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  91162. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91163. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91164. _this._dragBehaviorB.releaseDrag();
  91165. }
  91166. else {
  91167. _this._initialScale.copyFrom(ownerNode.scaling);
  91168. _this._startDistance = _this._getCurrentDistance();
  91169. }
  91170. }
  91171. });
  91172. // Once both drag behaviors are active scale based on the distance between the two pointers
  91173. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91174. behavior.onDragObservable.add(function () {
  91175. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91176. var ratio = _this._getCurrentDistance() / _this._startDistance;
  91177. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  91178. }
  91179. });
  91180. });
  91181. ownerNode.addBehavior(this._dragBehaviorA);
  91182. ownerNode.addBehavior(this._dragBehaviorB);
  91183. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91184. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91185. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91186. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  91187. if (change.length() > 0.01) {
  91188. ownerNode.scaling.addInPlace(change);
  91189. }
  91190. }
  91191. });
  91192. };
  91193. /**
  91194. * Detaches the behavior from the mesh
  91195. */
  91196. MultiPointerScaleBehavior.prototype.detach = function () {
  91197. var _this = this;
  91198. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91199. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91200. behavior.onDragStartObservable.clear();
  91201. behavior.onDragObservable.clear();
  91202. _this._ownerNode.removeBehavior(behavior);
  91203. });
  91204. };
  91205. return MultiPointerScaleBehavior;
  91206. }());
  91207. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  91208. })(BABYLON || (BABYLON = {}));
  91209. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  91210. var BABYLON;
  91211. (function (BABYLON) {
  91212. /**
  91213. * 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
  91214. */
  91215. var SixDofDragBehavior = /** @class */ (function () {
  91216. function SixDofDragBehavior() {
  91217. this._sceneRenderObserver = null;
  91218. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91219. this._moving = false;
  91220. this._startingOrientation = new BABYLON.Quaternion();
  91221. /**
  91222. * 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)
  91223. */
  91224. this.zDragFactor = 3;
  91225. /**
  91226. * If the behavior is currently in a dragging state
  91227. */
  91228. this.dragging = false;
  91229. /**
  91230. * 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)
  91231. */
  91232. this.dragDeltaRatio = 0.2;
  91233. /**
  91234. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91235. */
  91236. this.currentDraggingPointerID = -1;
  91237. /**
  91238. * If camera controls should be detached during the drag
  91239. */
  91240. this.detachCameraControls = true;
  91241. }
  91242. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  91243. /**
  91244. * The name of the behavior
  91245. */
  91246. get: function () {
  91247. return "SixDofDrag";
  91248. },
  91249. enumerable: true,
  91250. configurable: true
  91251. });
  91252. /**
  91253. * Initializes the behavior
  91254. */
  91255. SixDofDragBehavior.prototype.init = function () { };
  91256. /**
  91257. * Attaches the scale behavior the passed in mesh
  91258. * @param ownerNode The mesh that will be scaled around once attached
  91259. */
  91260. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91261. var _this = this;
  91262. this._ownerNode = ownerNode;
  91263. this._scene = this._ownerNode.getScene();
  91264. if (!SixDofDragBehavior._virtualScene) {
  91265. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91266. this._scene.getEngine().scenes.pop();
  91267. }
  91268. var pickedMesh = null;
  91269. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91270. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91271. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91272. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91273. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91274. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91275. var pickPredicate = function (m) {
  91276. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91277. };
  91278. var attachedElement = null;
  91279. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91280. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91281. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91282. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91283. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91284. }
  91285. pickedMesh = _this._ownerNode;
  91286. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91287. // Set position and orientation of the controller
  91288. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91289. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91290. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91291. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91292. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91293. if (!pickedMesh.rotationQuaternion) {
  91294. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91295. }
  91296. var oldParent = pickedMesh.parent;
  91297. pickedMesh.setParent(null);
  91298. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91299. pickedMesh.setParent(oldParent);
  91300. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91301. // Update state
  91302. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91303. _this.dragging = true;
  91304. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91305. // Detatch camera controls
  91306. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91307. if (_this._scene.activeCamera.inputs.attachedElement) {
  91308. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91309. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91310. }
  91311. else {
  91312. attachedElement = null;
  91313. }
  91314. }
  91315. }
  91316. }
  91317. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91318. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91319. _this.dragging = false;
  91320. _this._moving = false;
  91321. _this.currentDraggingPointerID = -1;
  91322. pickedMesh = null;
  91323. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91324. // Reattach camera controls
  91325. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91326. _this._scene.activeCamera.attachControl(attachedElement, true);
  91327. }
  91328. }
  91329. }
  91330. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91331. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91332. var zDragFactor = _this.zDragFactor;
  91333. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91334. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91335. zDragFactor = 0;
  91336. }
  91337. // Calculate controller drag distance in controller space
  91338. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91339. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91340. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91341. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91342. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91343. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91344. if (_this._virtualDragMesh.position.z < 0) {
  91345. _this._virtualDragMesh.position.z = 0;
  91346. }
  91347. // Update the controller position
  91348. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91349. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91350. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91351. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91352. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91353. if (pickedMesh.parent) {
  91354. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91355. }
  91356. if (!_this._moving) {
  91357. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91358. }
  91359. _this._moving = true;
  91360. }
  91361. }
  91362. });
  91363. var tmpQuaternion = new BABYLON.Quaternion();
  91364. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91365. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91366. if (_this.dragging && _this._moving && pickedMesh) {
  91367. // Slowly move mesh to avoid jitter
  91368. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91369. // Get change in rotation
  91370. tmpQuaternion.copyFrom(_this._startingOrientation);
  91371. tmpQuaternion.x = -tmpQuaternion.x;
  91372. tmpQuaternion.y = -tmpQuaternion.y;
  91373. tmpQuaternion.z = -tmpQuaternion.z;
  91374. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91375. // Convert change in rotation to only y axis rotation
  91376. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91377. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91378. // Slowly move mesh to avoid jitter
  91379. var oldParent = pickedMesh.parent;
  91380. pickedMesh.setParent(null);
  91381. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91382. pickedMesh.setParent(oldParent);
  91383. }
  91384. });
  91385. };
  91386. /**
  91387. * Detaches the behavior from the mesh
  91388. */
  91389. SixDofDragBehavior.prototype.detach = function () {
  91390. if (this._scene) {
  91391. this._scene.onPointerObservable.remove(this._pointerObserver);
  91392. }
  91393. if (this._ownerNode) {
  91394. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91395. }
  91396. if (this._virtualOriginMesh) {
  91397. this._virtualOriginMesh.dispose();
  91398. }
  91399. if (this._virtualDragMesh) {
  91400. this._virtualDragMesh.dispose();
  91401. }
  91402. };
  91403. return SixDofDragBehavior;
  91404. }());
  91405. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91406. })(BABYLON || (BABYLON = {}));
  91407. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91408. var BABYLON;
  91409. (function (BABYLON) {
  91410. /**
  91411. * @hidden
  91412. */
  91413. var FaceDirectionInfo = /** @class */ (function () {
  91414. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91415. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91416. if (diff === void 0) { diff = 0; }
  91417. if (ignore === void 0) { ignore = false; }
  91418. this.direction = direction;
  91419. this.rotatedDirection = rotatedDirection;
  91420. this.diff = diff;
  91421. this.ignore = ignore;
  91422. }
  91423. return FaceDirectionInfo;
  91424. }());
  91425. /**
  91426. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91427. */
  91428. var AttachToBoxBehavior = /** @class */ (function () {
  91429. /**
  91430. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91431. * @param ui The transform node that should be attched to the mesh
  91432. */
  91433. function AttachToBoxBehavior(ui) {
  91434. this.ui = ui;
  91435. /**
  91436. * The name of the behavior
  91437. */
  91438. this.name = "AttachToBoxBehavior";
  91439. /**
  91440. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91441. */
  91442. this.distanceAwayFromFace = 0.15;
  91443. /**
  91444. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91445. */
  91446. this.distanceAwayFromBottomOfFace = 0.15;
  91447. 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))];
  91448. this._tmpMatrix = new BABYLON.Matrix();
  91449. this._tmpVector = new BABYLON.Vector3();
  91450. this._zeroVector = BABYLON.Vector3.Zero();
  91451. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91452. /* Does nothing */
  91453. }
  91454. /**
  91455. * Initializes the behavior
  91456. */
  91457. AttachToBoxBehavior.prototype.init = function () {
  91458. /* Does nothing */
  91459. };
  91460. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91461. var _this = this;
  91462. // Go over each face and calculate the angle between the face's normal and targetDirection
  91463. this._faceVectors.forEach(function (v) {
  91464. if (!_this._target.rotationQuaternion) {
  91465. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91466. }
  91467. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  91468. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  91469. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  91470. });
  91471. // Return the face information of the one with the normal closeset to target direction
  91472. return this._faceVectors.reduce(function (min, p) {
  91473. if (min.ignore) {
  91474. return p;
  91475. }
  91476. else if (p.ignore) {
  91477. return min;
  91478. }
  91479. else {
  91480. return min.diff < p.diff ? min : p;
  91481. }
  91482. }, this._faceVectors[0]);
  91483. };
  91484. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  91485. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  91486. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  91487. this._lookAtTmpMatrix.invert();
  91488. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  91489. };
  91490. /**
  91491. * Attaches the AttachToBoxBehavior to the passed in mesh
  91492. * @param target The mesh that the specified node will be attached to
  91493. */
  91494. AttachToBoxBehavior.prototype.attach = function (target) {
  91495. var _this = this;
  91496. this._target = target;
  91497. this._scene = this._target.getScene();
  91498. // Every frame, update the app bars position
  91499. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91500. if (!_this._scene.activeCamera) {
  91501. return;
  91502. }
  91503. // Find the face closest to the cameras position
  91504. var cameraPos = _this._scene.activeCamera.position;
  91505. if (_this._scene.activeCamera.devicePosition) {
  91506. cameraPos = _this._scene.activeCamera.devicePosition;
  91507. }
  91508. var facing = _this._closestFace(cameraPos.subtract(target.position));
  91509. if (_this._scene.activeCamera.leftCamera) {
  91510. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91511. }
  91512. else {
  91513. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91514. }
  91515. // Get camera up direction
  91516. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  91517. // Ignore faces to not select a parrelel face for the up vector of the UI
  91518. _this._faceVectors.forEach(function (v) {
  91519. if (facing.direction.x && v.direction.x) {
  91520. v.ignore = true;
  91521. }
  91522. if (facing.direction.y && v.direction.y) {
  91523. v.ignore = true;
  91524. }
  91525. if (facing.direction.z && v.direction.z) {
  91526. v.ignore = true;
  91527. }
  91528. });
  91529. var facingUp = _this._closestFace(_this._tmpVector);
  91530. // Unignore faces
  91531. _this._faceVectors.forEach(function (v) {
  91532. v.ignore = false;
  91533. });
  91534. // Position the app bar on that face
  91535. _this.ui.position.copyFrom(target.position);
  91536. if (facing.direction.x) {
  91537. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91538. _this.ui.position.addInPlace(_this._tmpVector);
  91539. }
  91540. if (facing.direction.y) {
  91541. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91542. _this.ui.position.addInPlace(_this._tmpVector);
  91543. }
  91544. if (facing.direction.z) {
  91545. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91546. _this.ui.position.addInPlace(_this._tmpVector);
  91547. }
  91548. // Rotate to be oriented properly to the camera
  91549. if (!_this.ui.rotationQuaternion) {
  91550. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  91551. }
  91552. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  91553. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  91554. // Place ui the correct distance from the bottom of the mesh
  91555. if (facingUp.direction.x) {
  91556. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  91557. }
  91558. if (facingUp.direction.y) {
  91559. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  91560. }
  91561. if (facingUp.direction.z) {
  91562. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  91563. }
  91564. _this.ui.position.addInPlace(_this._tmpVector);
  91565. });
  91566. };
  91567. /**
  91568. * Detaches the behavior from the mesh
  91569. */
  91570. AttachToBoxBehavior.prototype.detach = function () {
  91571. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  91572. };
  91573. return AttachToBoxBehavior;
  91574. }());
  91575. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  91576. })(BABYLON || (BABYLON = {}));
  91577. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  91578. var BABYLON;
  91579. (function (BABYLON) {
  91580. /**
  91581. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  91582. */
  91583. var FadeInOutBehavior = /** @class */ (function () {
  91584. /**
  91585. * Instatiates the FadeInOutBehavior
  91586. */
  91587. function FadeInOutBehavior() {
  91588. var _this = this;
  91589. /**
  91590. * Time in milliseconds to delay before fading in (Default: 0)
  91591. */
  91592. this.delay = 0;
  91593. /**
  91594. * Time in milliseconds for the mesh to fade in (Default: 300)
  91595. */
  91596. this.fadeInTime = 300;
  91597. this._millisecondsPerFrame = 1000 / 60;
  91598. this._hovered = false;
  91599. this._hoverValue = 0;
  91600. this._ownerNode = null;
  91601. this._update = function () {
  91602. if (_this._ownerNode) {
  91603. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  91604. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  91605. if (_this._ownerNode.visibility > 1) {
  91606. _this._setAllVisibility(_this._ownerNode, 1);
  91607. _this._hoverValue = _this.fadeInTime + _this.delay;
  91608. return;
  91609. }
  91610. else if (_this._ownerNode.visibility < 0) {
  91611. _this._setAllVisibility(_this._ownerNode, 0);
  91612. if (_this._hoverValue < 0) {
  91613. _this._hoverValue = 0;
  91614. return;
  91615. }
  91616. }
  91617. setTimeout(_this._update, _this._millisecondsPerFrame);
  91618. }
  91619. };
  91620. }
  91621. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  91622. /**
  91623. * The name of the behavior
  91624. */
  91625. get: function () {
  91626. return "FadeInOut";
  91627. },
  91628. enumerable: true,
  91629. configurable: true
  91630. });
  91631. /**
  91632. * Initializes the behavior
  91633. */
  91634. FadeInOutBehavior.prototype.init = function () {
  91635. };
  91636. /**
  91637. * Attaches the fade behavior on the passed in mesh
  91638. * @param ownerNode The mesh that will be faded in/out once attached
  91639. */
  91640. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  91641. this._ownerNode = ownerNode;
  91642. this._setAllVisibility(this._ownerNode, 0);
  91643. };
  91644. /**
  91645. * Detaches the behavior from the mesh
  91646. */
  91647. FadeInOutBehavior.prototype.detach = function () {
  91648. this._ownerNode = null;
  91649. };
  91650. /**
  91651. * Triggers the mesh to begin fading in or out
  91652. * @param value if the object should fade in or out (true to fade in)
  91653. */
  91654. FadeInOutBehavior.prototype.fadeIn = function (value) {
  91655. this._hovered = value;
  91656. this._update();
  91657. };
  91658. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  91659. var _this = this;
  91660. mesh.visibility = value;
  91661. mesh.getChildMeshes().forEach(function (c) {
  91662. _this._setAllVisibility(c, value);
  91663. });
  91664. };
  91665. return FadeInOutBehavior;
  91666. }());
  91667. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  91668. })(BABYLON || (BABYLON = {}));
  91669. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  91670. var BABYLON;
  91671. (function (BABYLON) {
  91672. /**
  91673. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  91674. */
  91675. var Gizmo = /** @class */ (function () {
  91676. /**
  91677. * Creates a gizmo
  91678. * @param gizmoLayer The utility layer the gizmo will be added to
  91679. */
  91680. function Gizmo(
  91681. /** The utility layer the gizmo will be added to */
  91682. gizmoLayer) {
  91683. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91684. var _this = this;
  91685. this.gizmoLayer = gizmoLayer;
  91686. /**
  91687. * Ratio for the scale of the gizmo (Default: 1)
  91688. */
  91689. this.scaleRatio = 1;
  91690. this._tmpMatrix = new BABYLON.Matrix();
  91691. /**
  91692. * If a custom mesh has been set (Default: false)
  91693. */
  91694. this._customMeshSet = false;
  91695. /**
  91696. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  91697. */
  91698. this.updateGizmoRotationToMatchAttachedMesh = true;
  91699. /**
  91700. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  91701. */
  91702. this.updateGizmoPositionToMatchAttachedMesh = true;
  91703. /**
  91704. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  91705. */
  91706. this._updateScale = true;
  91707. this._interactionsEnabled = true;
  91708. this._tempVector = new BABYLON.Vector3();
  91709. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  91710. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  91711. _this._update();
  91712. });
  91713. this.attachedMesh = null;
  91714. }
  91715. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  91716. /**
  91717. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  91718. * * When set, interactions will be enabled
  91719. */
  91720. get: function () {
  91721. return this._attachedMesh;
  91722. },
  91723. set: function (value) {
  91724. this._attachedMesh = value;
  91725. this._rootMesh.setEnabled(value ? true : false);
  91726. this._attachedMeshChanged(value);
  91727. },
  91728. enumerable: true,
  91729. configurable: true
  91730. });
  91731. /**
  91732. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  91733. * @param mesh The mesh to replace the default mesh of the gizmo
  91734. */
  91735. Gizmo.prototype.setCustomMesh = function (mesh) {
  91736. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  91737. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  91738. }
  91739. this._rootMesh.getChildMeshes().forEach(function (c) {
  91740. c.dispose();
  91741. });
  91742. mesh.parent = this._rootMesh;
  91743. this._customMeshSet = true;
  91744. };
  91745. Gizmo.prototype._attachedMeshChanged = function (value) {
  91746. };
  91747. /**
  91748. * @hidden
  91749. * Updates the gizmo to match the attached mesh's position/rotation
  91750. */
  91751. Gizmo.prototype._update = function () {
  91752. if (this.attachedMesh) {
  91753. if (this.updateGizmoRotationToMatchAttachedMesh) {
  91754. if (!this._rootMesh.rotationQuaternion) {
  91755. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  91756. }
  91757. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  91758. this._tempVector.copyFrom(this.attachedMesh.scaling);
  91759. if (this.attachedMesh.scaling.x < 0) {
  91760. this.attachedMesh.scaling.x *= -1;
  91761. }
  91762. if (this.attachedMesh.scaling.y < 0) {
  91763. this.attachedMesh.scaling.y *= -1;
  91764. }
  91765. if (this.attachedMesh.scaling.z < 0) {
  91766. this.attachedMesh.scaling.z *= -1;
  91767. }
  91768. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  91769. this.attachedMesh.scaling.copyFrom(this._tempVector);
  91770. this.attachedMesh.computeWorldMatrix();
  91771. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  91772. }
  91773. else if (this._rootMesh.rotationQuaternion) {
  91774. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  91775. }
  91776. if (this.updateGizmoPositionToMatchAttachedMesh) {
  91777. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  91778. }
  91779. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  91780. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  91781. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  91782. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  91783. }
  91784. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  91785. var dist = this._tempVector.length() * this.scaleRatio;
  91786. this._rootMesh.scaling.set(dist, dist, dist);
  91787. }
  91788. }
  91789. };
  91790. /**
  91791. * Disposes of the gizmo
  91792. */
  91793. Gizmo.prototype.dispose = function () {
  91794. this._rootMesh.dispose();
  91795. if (this._beforeRenderObserver) {
  91796. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91797. }
  91798. };
  91799. return Gizmo;
  91800. }());
  91801. BABYLON.Gizmo = Gizmo;
  91802. })(BABYLON || (BABYLON = {}));
  91803. //# sourceMappingURL=babylon.gizmo.js.map
  91804. var BABYLON;
  91805. (function (BABYLON) {
  91806. /**
  91807. * Single axis drag gizmo
  91808. */
  91809. var AxisDragGizmo = /** @class */ (function (_super) {
  91810. __extends(AxisDragGizmo, _super);
  91811. /**
  91812. * Creates an AxisDragGizmo
  91813. * @param gizmoLayer The utility layer the gizmo will be added to
  91814. * @param dragAxis The axis which the gizmo will be able to drag on
  91815. * @param color The color of the gizmo
  91816. */
  91817. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  91818. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91819. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91820. var _this = _super.call(this, gizmoLayer) || this;
  91821. _this._pointerObserver = null;
  91822. /**
  91823. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91824. */
  91825. _this.snapDistance = 0;
  91826. /**
  91827. * Event that fires each time the gizmo snaps to a new location.
  91828. * * snapDistance is the the change in distance
  91829. */
  91830. _this.onSnapObservable = new BABYLON.Observable();
  91831. // Create Material
  91832. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91833. coloredMaterial.disableLighting = true;
  91834. coloredMaterial.emissiveColor = color;
  91835. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91836. hoverMaterial.disableLighting = true;
  91837. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  91838. // Build mesh on root node
  91839. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91840. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  91841. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  91842. arrowTail.color = coloredMaterial.emissiveColor;
  91843. arrow.addChild(arrowMesh);
  91844. arrow.addChild(arrowTail);
  91845. // Position arrow pointing in its drag axis
  91846. arrowMesh.scaling.scaleInPlace(0.05);
  91847. arrowMesh.material = coloredMaterial;
  91848. arrowMesh.rotation.x = Math.PI / 2;
  91849. arrowMesh.position.z += 0.3;
  91850. arrowTail.scaling.scaleInPlace(0.26);
  91851. arrowTail.rotation.x = Math.PI / 2;
  91852. arrowTail.material = coloredMaterial;
  91853. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  91854. arrow.scaling.scaleInPlace(1 / 3);
  91855. _this._rootMesh.addChild(arrow);
  91856. var currentSnapDragDistance = 0;
  91857. var tmpVector = new BABYLON.Vector3();
  91858. var tmpSnapEvent = { snapDistance: 0 };
  91859. // Add drag behavior to handle events when the gizmo is dragged
  91860. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91861. _this.dragBehavior.moveAttached = false;
  91862. _this._rootMesh.addBehavior(_this.dragBehavior);
  91863. var localDelta = new BABYLON.Vector3();
  91864. var tmpMatrix = new BABYLON.Matrix();
  91865. _this.dragBehavior.onDragObservable.add(function (event) {
  91866. if (_this.attachedMesh) {
  91867. // Convert delta to local translation if it has a parent
  91868. if (_this.attachedMesh.parent) {
  91869. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  91870. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  91871. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  91872. }
  91873. else {
  91874. localDelta.copyFrom(event.delta);
  91875. }
  91876. // Snapping logic
  91877. if (_this.snapDistance == 0) {
  91878. _this.attachedMesh.position.addInPlace(localDelta);
  91879. }
  91880. else {
  91881. currentSnapDragDistance += event.dragDistance;
  91882. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91883. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  91884. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91885. localDelta.normalizeToRef(tmpVector);
  91886. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  91887. _this.attachedMesh.position.addInPlace(tmpVector);
  91888. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  91889. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91890. }
  91891. }
  91892. }
  91893. });
  91894. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91895. if (_this._customMeshSet) {
  91896. return;
  91897. }
  91898. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91899. var material = isHovered ? hoverMaterial : coloredMaterial;
  91900. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91901. m.material = material;
  91902. if (m.color) {
  91903. m.color = material.emissiveColor;
  91904. }
  91905. });
  91906. });
  91907. return _this;
  91908. }
  91909. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  91910. if (this.dragBehavior) {
  91911. this.dragBehavior.enabled = value ? true : false;
  91912. }
  91913. };
  91914. /**
  91915. * Disposes of the gizmo
  91916. */
  91917. AxisDragGizmo.prototype.dispose = function () {
  91918. this.onSnapObservable.clear();
  91919. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91920. this.dragBehavior.detach();
  91921. _super.prototype.dispose.call(this);
  91922. };
  91923. return AxisDragGizmo;
  91924. }(BABYLON.Gizmo));
  91925. BABYLON.AxisDragGizmo = AxisDragGizmo;
  91926. })(BABYLON || (BABYLON = {}));
  91927. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  91928. var BABYLON;
  91929. (function (BABYLON) {
  91930. /**
  91931. * Single axis scale gizmo
  91932. */
  91933. var AxisScaleGizmo = /** @class */ (function (_super) {
  91934. __extends(AxisScaleGizmo, _super);
  91935. /**
  91936. * Creates an AxisScaleGizmo
  91937. * @param gizmoLayer The utility layer the gizmo will be added to
  91938. * @param dragAxis The axis which the gizmo will be able to scale on
  91939. * @param color The color of the gizmo
  91940. */
  91941. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  91942. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91943. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91944. var _this = _super.call(this, gizmoLayer) || this;
  91945. _this._pointerObserver = null;
  91946. /**
  91947. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91948. */
  91949. _this.snapDistance = 0;
  91950. /**
  91951. * Event that fires each time the gizmo snaps to a new location.
  91952. * * snapDistance is the the change in distance
  91953. */
  91954. _this.onSnapObservable = new BABYLON.Observable();
  91955. /**
  91956. * If the scaling operation should be done on all axis (default: false)
  91957. */
  91958. _this.uniformScaling = false;
  91959. // Create Material
  91960. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91961. _this._coloredMaterial.disableLighting = true;
  91962. _this._coloredMaterial.emissiveColor = color;
  91963. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91964. hoverMaterial.disableLighting = true;
  91965. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  91966. // Build mesh on root node
  91967. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91968. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  91969. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  91970. arrowTail.color = _this._coloredMaterial.emissiveColor;
  91971. arrow.addChild(arrowMesh);
  91972. arrow.addChild(arrowTail);
  91973. // Position arrow pointing in its drag axis
  91974. arrowMesh.scaling.scaleInPlace(0.1);
  91975. arrowMesh.material = _this._coloredMaterial;
  91976. arrowMesh.rotation.x = Math.PI / 2;
  91977. arrowMesh.position.z += 0.3;
  91978. arrowTail.scaling.scaleInPlace(0.26);
  91979. arrowTail.rotation.x = Math.PI / 2;
  91980. arrowTail.material = _this._coloredMaterial;
  91981. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  91982. _this._rootMesh.addChild(arrow);
  91983. arrow.scaling.scaleInPlace(1 / 3);
  91984. // Add drag behavior to handle events when the gizmo is dragged
  91985. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91986. _this.dragBehavior.moveAttached = false;
  91987. _this._rootMesh.addBehavior(_this.dragBehavior);
  91988. var currentSnapDragDistance = 0;
  91989. var tmpVector = new BABYLON.Vector3();
  91990. var tmpSnapEvent = { snapDistance: 0 };
  91991. _this.dragBehavior.onDragObservable.add(function (event) {
  91992. if (_this.attachedMesh) {
  91993. // Snapping logic
  91994. var snapped = false;
  91995. var dragSteps = 0;
  91996. if (_this.uniformScaling) {
  91997. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  91998. if (tmpVector.y < 0) {
  91999. tmpVector.scaleInPlace(-1);
  92000. }
  92001. }
  92002. else {
  92003. tmpVector.copyFrom(dragAxis);
  92004. }
  92005. if (_this.snapDistance == 0) {
  92006. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92007. }
  92008. else {
  92009. currentSnapDragDistance += event.dragDistance;
  92010. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92011. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92012. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92013. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92014. snapped = true;
  92015. }
  92016. else {
  92017. tmpVector.scaleInPlace(0);
  92018. }
  92019. }
  92020. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92021. if (snapped) {
  92022. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92023. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92024. }
  92025. }
  92026. });
  92027. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92028. if (_this._customMeshSet) {
  92029. return;
  92030. }
  92031. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92032. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  92033. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92034. m.material = material;
  92035. if (m.color) {
  92036. m.color = material.emissiveColor;
  92037. }
  92038. });
  92039. });
  92040. return _this;
  92041. }
  92042. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  92043. if (this.dragBehavior) {
  92044. this.dragBehavior.enabled = value ? true : false;
  92045. }
  92046. };
  92047. /**
  92048. * Disposes of the gizmo
  92049. */
  92050. AxisScaleGizmo.prototype.dispose = function () {
  92051. this.onSnapObservable.clear();
  92052. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92053. this.dragBehavior.detach();
  92054. _super.prototype.dispose.call(this);
  92055. };
  92056. /**
  92057. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92058. * @param mesh The mesh to replace the default mesh of the gizmo
  92059. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  92060. */
  92061. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  92062. var _this = this;
  92063. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  92064. _super.prototype.setCustomMesh.call(this, mesh);
  92065. if (useGizmoMaterial) {
  92066. this._rootMesh.getChildMeshes().forEach(function (m) {
  92067. m.material = _this._coloredMaterial;
  92068. if (m.color) {
  92069. m.color = _this._coloredMaterial.emissiveColor;
  92070. }
  92071. });
  92072. this._customMeshSet = false;
  92073. }
  92074. };
  92075. return AxisScaleGizmo;
  92076. }(BABYLON.Gizmo));
  92077. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  92078. })(BABYLON || (BABYLON = {}));
  92079. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  92080. var BABYLON;
  92081. (function (BABYLON) {
  92082. /**
  92083. * Single plane rotation gizmo
  92084. */
  92085. var PlaneRotationGizmo = /** @class */ (function (_super) {
  92086. __extends(PlaneRotationGizmo, _super);
  92087. /**
  92088. * Creates a PlaneRotationGizmo
  92089. * @param gizmoLayer The utility layer the gizmo will be added to
  92090. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  92091. * @param color The color of the gizmo
  92092. */
  92093. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  92094. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92095. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92096. var _this = _super.call(this, gizmoLayer) || this;
  92097. _this._pointerObserver = null;
  92098. /**
  92099. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  92100. */
  92101. _this.snapDistance = 0;
  92102. /**
  92103. * Event that fires each time the gizmo snaps to a new location.
  92104. * * snapDistance is the the change in distance
  92105. */
  92106. _this.onSnapObservable = new BABYLON.Observable();
  92107. // Create Material
  92108. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92109. coloredMaterial.disableLighting = true;
  92110. coloredMaterial.emissiveColor = color;
  92111. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92112. hoverMaterial.disableLighting = true;
  92113. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92114. // Build mesh on root node
  92115. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92116. // Create circle out of lines
  92117. var tessellation = 20;
  92118. var radius = 0.8;
  92119. var points = new Array();
  92120. for (var i = 0; i < tessellation; i++) {
  92121. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  92122. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  92123. }
  92124. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  92125. rotationMesh.color = coloredMaterial.emissiveColor;
  92126. // Position arrow pointing in its drag axis
  92127. rotationMesh.scaling.scaleInPlace(0.26);
  92128. rotationMesh.material = coloredMaterial;
  92129. rotationMesh.rotation.x = Math.PI / 2;
  92130. parentMesh.addChild(rotationMesh);
  92131. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  92132. _this._rootMesh.addChild(parentMesh);
  92133. parentMesh.scaling.scaleInPlace(1 / 3);
  92134. // Add drag behavior to handle events when the gizmo is dragged
  92135. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  92136. _this.dragBehavior.moveAttached = false;
  92137. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  92138. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  92139. _this._rootMesh.addBehavior(_this.dragBehavior);
  92140. var lastDragPosition = new BABYLON.Vector3();
  92141. _this.dragBehavior.onDragStartObservable.add(function (e) {
  92142. if (_this.attachedMesh) {
  92143. lastDragPosition.copyFrom(e.dragPlanePoint);
  92144. }
  92145. });
  92146. var rotationMatrix = new BABYLON.Matrix();
  92147. var planeNormalTowardsCamera = new BABYLON.Vector3();
  92148. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  92149. var tmpSnapEvent = { snapDistance: 0 };
  92150. var currentSnapDragDistance = 0;
  92151. var tmpMatrix = new BABYLON.Matrix();
  92152. var tmpVector = new BABYLON.Vector3();
  92153. var amountToRotate = new BABYLON.Quaternion();
  92154. _this.dragBehavior.onDragObservable.add(function (event) {
  92155. if (_this.attachedMesh) {
  92156. if (!_this.attachedMesh.rotationQuaternion) {
  92157. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92158. }
  92159. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  92160. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  92161. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  92162. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  92163. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  92164. var angle = Math.atan2(cross.length(), dot);
  92165. planeNormalTowardsCamera.copyFrom(planeNormal);
  92166. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  92167. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92168. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  92169. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  92170. }
  92171. // Flip up vector depending on which side the camera is on
  92172. if (gizmoLayer.utilityLayerScene.activeCamera) {
  92173. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  92174. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  92175. planeNormalTowardsCamera.scaleInPlace(-1);
  92176. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  92177. }
  92178. }
  92179. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  92180. if (halfCircleSide)
  92181. angle = -angle;
  92182. // Snapping logic
  92183. var snapped = false;
  92184. if (_this.snapDistance != 0) {
  92185. currentSnapDragDistance += angle;
  92186. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92187. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92188. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92189. angle = _this.snapDistance * dragSteps;
  92190. snapped = true;
  92191. }
  92192. else {
  92193. angle = 0;
  92194. }
  92195. }
  92196. // If the mesh has a parent, convert needed world rotation to local rotation
  92197. tmpMatrix.reset();
  92198. if (_this.attachedMesh.parent) {
  92199. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92200. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  92201. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  92202. }
  92203. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  92204. var quaternionCoefficient = Math.sin(angle / 2);
  92205. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  92206. // 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
  92207. if (tmpMatrix.determinant() > 0) {
  92208. amountToRotate.toEulerAnglesToRef(tmpVector);
  92209. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  92210. }
  92211. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92212. // Rotate selected mesh quaternion over fixed axis
  92213. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  92214. }
  92215. else {
  92216. // Rotate selected mesh quaternion over rotated axis
  92217. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  92218. }
  92219. lastDragPosition.copyFrom(event.dragPlanePoint);
  92220. if (snapped) {
  92221. tmpSnapEvent.snapDistance = angle;
  92222. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92223. }
  92224. }
  92225. });
  92226. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92227. if (_this._customMeshSet) {
  92228. return;
  92229. }
  92230. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92231. var material = isHovered ? hoverMaterial : coloredMaterial;
  92232. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92233. m.material = material;
  92234. if (m.color) {
  92235. m.color = material.emissiveColor;
  92236. }
  92237. });
  92238. });
  92239. return _this;
  92240. }
  92241. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  92242. if (this.dragBehavior) {
  92243. this.dragBehavior.enabled = value ? true : false;
  92244. }
  92245. };
  92246. /**
  92247. * Disposes of the gizmo
  92248. */
  92249. PlaneRotationGizmo.prototype.dispose = function () {
  92250. this.onSnapObservable.clear();
  92251. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92252. this.dragBehavior.detach();
  92253. _super.prototype.dispose.call(this);
  92254. };
  92255. return PlaneRotationGizmo;
  92256. }(BABYLON.Gizmo));
  92257. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  92258. })(BABYLON || (BABYLON = {}));
  92259. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  92260. var BABYLON;
  92261. (function (BABYLON) {
  92262. /**
  92263. * Gizmo that enables dragging a mesh along 3 axis
  92264. */
  92265. var PositionGizmo = /** @class */ (function (_super) {
  92266. __extends(PositionGizmo, _super);
  92267. /**
  92268. * Creates a PositionGizmo
  92269. * @param gizmoLayer The utility layer the gizmo will be added to
  92270. */
  92271. function PositionGizmo(gizmoLayer) {
  92272. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92273. var _this = _super.call(this, gizmoLayer) || this;
  92274. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92275. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92276. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92277. _this.attachedMesh = null;
  92278. return _this;
  92279. }
  92280. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  92281. set: function (mesh) {
  92282. if (this.xGizmo) {
  92283. this.xGizmo.attachedMesh = mesh;
  92284. this.yGizmo.attachedMesh = mesh;
  92285. this.zGizmo.attachedMesh = mesh;
  92286. }
  92287. },
  92288. enumerable: true,
  92289. configurable: true
  92290. });
  92291. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92292. get: function () {
  92293. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92294. },
  92295. set: function (value) {
  92296. if (this.xGizmo) {
  92297. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92298. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92299. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92300. }
  92301. },
  92302. enumerable: true,
  92303. configurable: true
  92304. });
  92305. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  92306. get: function () {
  92307. return this.xGizmo.snapDistance;
  92308. },
  92309. /**
  92310. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92311. */
  92312. set: function (value) {
  92313. if (this.xGizmo) {
  92314. this.xGizmo.snapDistance = value;
  92315. this.yGizmo.snapDistance = value;
  92316. this.zGizmo.snapDistance = value;
  92317. }
  92318. },
  92319. enumerable: true,
  92320. configurable: true
  92321. });
  92322. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  92323. get: function () {
  92324. return this.xGizmo.scaleRatio;
  92325. },
  92326. /**
  92327. * Ratio for the scale of the gizmo (Default: 1)
  92328. */
  92329. set: function (value) {
  92330. if (this.xGizmo) {
  92331. this.xGizmo.scaleRatio = value;
  92332. this.yGizmo.scaleRatio = value;
  92333. this.zGizmo.scaleRatio = value;
  92334. }
  92335. },
  92336. enumerable: true,
  92337. configurable: true
  92338. });
  92339. /**
  92340. * Disposes of the gizmo
  92341. */
  92342. PositionGizmo.prototype.dispose = function () {
  92343. this.xGizmo.dispose();
  92344. this.yGizmo.dispose();
  92345. this.zGizmo.dispose();
  92346. };
  92347. /**
  92348. * CustomMeshes are not supported by this gizmo
  92349. * @param mesh The mesh to replace the default mesh of the gizmo
  92350. */
  92351. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92352. 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)");
  92353. };
  92354. return PositionGizmo;
  92355. }(BABYLON.Gizmo));
  92356. BABYLON.PositionGizmo = PositionGizmo;
  92357. })(BABYLON || (BABYLON = {}));
  92358. //# sourceMappingURL=babylon.positionGizmo.js.map
  92359. var BABYLON;
  92360. (function (BABYLON) {
  92361. /**
  92362. * Gizmo that enables rotating a mesh along 3 axis
  92363. */
  92364. var RotationGizmo = /** @class */ (function (_super) {
  92365. __extends(RotationGizmo, _super);
  92366. /**
  92367. * Creates a RotationGizmo
  92368. * @param gizmoLayer The utility layer the gizmo will be added to
  92369. */
  92370. function RotationGizmo(gizmoLayer) {
  92371. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92372. var _this = _super.call(this, gizmoLayer) || this;
  92373. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92374. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92375. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92376. _this.attachedMesh = null;
  92377. return _this;
  92378. }
  92379. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92380. set: function (mesh) {
  92381. if (this.xGizmo) {
  92382. this.xGizmo.attachedMesh = mesh;
  92383. this.yGizmo.attachedMesh = mesh;
  92384. this.zGizmo.attachedMesh = mesh;
  92385. }
  92386. },
  92387. enumerable: true,
  92388. configurable: true
  92389. });
  92390. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92391. get: function () {
  92392. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92393. },
  92394. set: function (value) {
  92395. if (this.xGizmo) {
  92396. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92397. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92398. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92399. }
  92400. },
  92401. enumerable: true,
  92402. configurable: true
  92403. });
  92404. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92405. get: function () {
  92406. return this.xGizmo.snapDistance;
  92407. },
  92408. /**
  92409. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92410. */
  92411. set: function (value) {
  92412. if (this.xGizmo) {
  92413. this.xGizmo.snapDistance = value;
  92414. this.yGizmo.snapDistance = value;
  92415. this.zGizmo.snapDistance = value;
  92416. }
  92417. },
  92418. enumerable: true,
  92419. configurable: true
  92420. });
  92421. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92422. get: function () {
  92423. return this.xGizmo.scaleRatio;
  92424. },
  92425. /**
  92426. * Ratio for the scale of the gizmo (Default: 1)
  92427. */
  92428. set: function (value) {
  92429. if (this.xGizmo) {
  92430. this.xGizmo.scaleRatio = value;
  92431. this.yGizmo.scaleRatio = value;
  92432. this.zGizmo.scaleRatio = value;
  92433. }
  92434. },
  92435. enumerable: true,
  92436. configurable: true
  92437. });
  92438. /**
  92439. * Disposes of the gizmo
  92440. */
  92441. RotationGizmo.prototype.dispose = function () {
  92442. this.xGizmo.dispose();
  92443. this.yGizmo.dispose();
  92444. this.zGizmo.dispose();
  92445. };
  92446. /**
  92447. * CustomMeshes are not supported by this gizmo
  92448. * @param mesh The mesh to replace the default mesh of the gizmo
  92449. */
  92450. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92451. 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)");
  92452. };
  92453. return RotationGizmo;
  92454. }(BABYLON.Gizmo));
  92455. BABYLON.RotationGizmo = RotationGizmo;
  92456. })(BABYLON || (BABYLON = {}));
  92457. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92458. var BABYLON;
  92459. (function (BABYLON) {
  92460. /**
  92461. * Gizmo that enables scaling a mesh along 3 axis
  92462. */
  92463. var ScaleGizmo = /** @class */ (function (_super) {
  92464. __extends(ScaleGizmo, _super);
  92465. /**
  92466. * Creates a ScaleGizmo
  92467. * @param gizmoLayer The utility layer the gizmo will be added to
  92468. */
  92469. function ScaleGizmo(gizmoLayer) {
  92470. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92471. var _this = _super.call(this, gizmoLayer) || this;
  92472. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92473. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92474. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92475. // Create uniform scale gizmo
  92476. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  92477. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92478. _this._uniformGizmo.uniformScaling = true;
  92479. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  92480. octahedron.scaling.scaleInPlace(0.007);
  92481. _this._uniformGizmo.setCustomMesh(octahedron, true);
  92482. _this.attachedMesh = null;
  92483. return _this;
  92484. }
  92485. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  92486. set: function (mesh) {
  92487. if (this.xGizmo) {
  92488. this.xGizmo.attachedMesh = mesh;
  92489. this.yGizmo.attachedMesh = mesh;
  92490. this.zGizmo.attachedMesh = mesh;
  92491. this._uniformGizmo.attachedMesh = mesh;
  92492. }
  92493. },
  92494. enumerable: true,
  92495. configurable: true
  92496. });
  92497. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92498. get: function () {
  92499. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92500. },
  92501. set: function (value) {
  92502. if (this.xGizmo) {
  92503. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92504. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92505. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92506. }
  92507. },
  92508. enumerable: true,
  92509. configurable: true
  92510. });
  92511. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  92512. get: function () {
  92513. return this.xGizmo.snapDistance;
  92514. },
  92515. /**
  92516. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92517. */
  92518. set: function (value) {
  92519. if (this.xGizmo) {
  92520. this.xGizmo.snapDistance = value;
  92521. this.yGizmo.snapDistance = value;
  92522. this.zGizmo.snapDistance = value;
  92523. this._uniformGizmo.snapDistance = value;
  92524. }
  92525. },
  92526. enumerable: true,
  92527. configurable: true
  92528. });
  92529. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  92530. get: function () {
  92531. return this.xGizmo.scaleRatio;
  92532. },
  92533. /**
  92534. * Ratio for the scale of the gizmo (Default: 1)
  92535. */
  92536. set: function (value) {
  92537. if (this.xGizmo) {
  92538. this.xGizmo.scaleRatio = value;
  92539. this.yGizmo.scaleRatio = value;
  92540. this.zGizmo.scaleRatio = value;
  92541. this._uniformGizmo.scaleRatio = value;
  92542. }
  92543. },
  92544. enumerable: true,
  92545. configurable: true
  92546. });
  92547. /**
  92548. * Disposes of the gizmo
  92549. */
  92550. ScaleGizmo.prototype.dispose = function () {
  92551. this.xGizmo.dispose();
  92552. this.yGizmo.dispose();
  92553. this.zGizmo.dispose();
  92554. this._uniformGizmo.dispose();
  92555. };
  92556. return ScaleGizmo;
  92557. }(BABYLON.Gizmo));
  92558. BABYLON.ScaleGizmo = ScaleGizmo;
  92559. })(BABYLON || (BABYLON = {}));
  92560. //# sourceMappingURL=babylon.scaleGizmo.js.map
  92561. var BABYLON;
  92562. (function (BABYLON) {
  92563. /**
  92564. * Bounding box gizmo
  92565. */
  92566. var BoundingBoxGizmo = /** @class */ (function (_super) {
  92567. __extends(BoundingBoxGizmo, _super);
  92568. /**
  92569. * Creates an BoundingBoxGizmo
  92570. * @param gizmoLayer The utility layer the gizmo will be added to
  92571. * @param color The color of the gizmo
  92572. */
  92573. function BoundingBoxGizmo(color, gizmoLayer) {
  92574. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92575. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  92576. var _this = _super.call(this, gizmoLayer) || this;
  92577. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  92578. _this._renderObserver = null;
  92579. _this._pointerObserver = null;
  92580. _this._scaleDragSpeed = 0.2;
  92581. _this._tmpQuaternion = new BABYLON.Quaternion();
  92582. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92583. /**
  92584. * 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)
  92585. */
  92586. _this.ignoreChildren = false;
  92587. /**
  92588. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  92589. */
  92590. _this.rotationSphereSize = 0.1;
  92591. /**
  92592. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  92593. */
  92594. _this.scaleBoxSize = 0.1;
  92595. /**
  92596. * 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)
  92597. */
  92598. _this.fixedDragMeshScreenSize = false;
  92599. /**
  92600. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  92601. */
  92602. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  92603. /**
  92604. * Fired when a rotation sphere or scale box is dragged
  92605. */
  92606. _this.onDragStartObservable = new BABYLON.Observable();
  92607. /**
  92608. * Fired when a scale box is dragged
  92609. */
  92610. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  92611. /**
  92612. * Fired when a scale box drag is ended
  92613. */
  92614. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  92615. /**
  92616. * Fired when a rotation sphere is dragged
  92617. */
  92618. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  92619. /**
  92620. * Fired when a rotation sphere drag is ended
  92621. */
  92622. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  92623. _this._existingMeshScale = new BABYLON.Vector3();
  92624. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  92625. _this._updateScale = false;
  92626. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  92627. // Create Materials
  92628. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92629. coloredMaterial.disableLighting = true;
  92630. coloredMaterial.emissiveColor = color;
  92631. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92632. hoverColoredMaterial.disableLighting = true;
  92633. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92634. // Build bounding box out of lines
  92635. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92636. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  92637. var lines = [];
  92638. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  92639. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92640. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92641. 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));
  92642. 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));
  92643. 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));
  92644. 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));
  92645. 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));
  92646. 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));
  92647. 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));
  92648. 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));
  92649. 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));
  92650. lines.forEach(function (l) {
  92651. l.color = color;
  92652. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  92653. l.isPickable = false;
  92654. _this._lineBoundingBox.addChild(l);
  92655. });
  92656. _this._rootMesh.addChild(_this._lineBoundingBox);
  92657. // Create rotation spheres
  92658. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92659. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  92660. var _loop_1 = function (i_1) {
  92661. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  92662. sphere.rotationQuaternion = new BABYLON.Quaternion();
  92663. sphere.material = coloredMaterial;
  92664. // Drag behavior
  92665. _dragBehavior = new BABYLON.PointerDragBehavior({});
  92666. _dragBehavior.moveAttached = false;
  92667. _dragBehavior.updateDragPlane = false;
  92668. sphere.addBehavior(_dragBehavior);
  92669. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  92670. var totalTurnAmountOfDrag = 0;
  92671. _dragBehavior.onDragStartObservable.add(function (event) {
  92672. startingTurnDirection.copyFrom(sphere.forward);
  92673. totalTurnAmountOfDrag = 0;
  92674. });
  92675. _dragBehavior.onDragObservable.add(function (event) {
  92676. _this.onRotationSphereDragObservable.notifyObservers({});
  92677. if (_this.attachedMesh) {
  92678. var worldDragDirection = startingTurnDirection;
  92679. // Project the world right on to the drag plane
  92680. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  92681. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  92682. // project drag delta on to the resulting drag axis and rotate based on that
  92683. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  92684. // Make rotation relative to size of mesh.
  92685. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  92686. // Rotate based on axis
  92687. if (!_this.attachedMesh.rotationQuaternion) {
  92688. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92689. }
  92690. if (!_this._anchorMesh.rotationQuaternion) {
  92691. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  92692. }
  92693. // Do not allow the object to turn more than a full circle
  92694. totalTurnAmountOfDrag += projectDist;
  92695. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  92696. if (i_1 >= 8) {
  92697. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  92698. }
  92699. else if (i_1 >= 4) {
  92700. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  92701. }
  92702. else {
  92703. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  92704. }
  92705. // Rotate around center of bounding box
  92706. _this._anchorMesh.addChild(_this.attachedMesh);
  92707. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  92708. _this._anchorMesh.removeChild(_this.attachedMesh);
  92709. }
  92710. _this.updateBoundingBox();
  92711. }
  92712. });
  92713. // Selection/deselection
  92714. _dragBehavior.onDragStartObservable.add(function () {
  92715. _this.onDragStartObservable.notifyObservers({});
  92716. _this._selectNode(sphere);
  92717. });
  92718. _dragBehavior.onDragEndObservable.add(function () {
  92719. _this.onRotationSphereDragEndObservable.notifyObservers({});
  92720. _this._selectNode(null);
  92721. });
  92722. this_1._rotateSpheresParent.addChild(sphere);
  92723. };
  92724. var this_1 = this, _dragBehavior;
  92725. for (var i_1 = 0; i_1 < 12; i_1++) {
  92726. _loop_1(i_1);
  92727. }
  92728. _this._rootMesh.addChild(_this._rotateSpheresParent);
  92729. // Create scale cubes
  92730. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92731. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  92732. for (var i = 0; i < 2; i++) {
  92733. for (var j = 0; j < 2; j++) {
  92734. var _loop_2 = function () {
  92735. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  92736. box.material = coloredMaterial;
  92737. // Dragging logic
  92738. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  92739. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92740. _dragBehavior.moveAttached = false;
  92741. box.addBehavior(_dragBehavior);
  92742. _dragBehavior.onDragObservable.add(function (event) {
  92743. _this.onScaleBoxDragObservable.notifyObservers({});
  92744. if (_this.attachedMesh) {
  92745. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  92746. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  92747. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  92748. _this.updateBoundingBox();
  92749. // Scale from the position of the opposite corner
  92750. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  92751. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  92752. _this._anchorMesh.addChild(_this.attachedMesh);
  92753. _this._anchorMesh.scaling.addInPlace(deltaScale);
  92754. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  92755. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  92756. }
  92757. _this._anchorMesh.removeChild(_this.attachedMesh);
  92758. }
  92759. });
  92760. // Selection/deselection
  92761. _dragBehavior.onDragStartObservable.add(function () {
  92762. _this.onDragStartObservable.notifyObservers({});
  92763. _this._selectNode(box);
  92764. });
  92765. _dragBehavior.onDragEndObservable.add(function () {
  92766. _this.onScaleBoxDragEndObservable.notifyObservers({});
  92767. _this._selectNode(null);
  92768. });
  92769. this_2._scaleBoxesParent.addChild(box);
  92770. };
  92771. var this_2 = this, _dragBehavior;
  92772. for (var k = 0; k < 2; k++) {
  92773. _loop_2();
  92774. }
  92775. }
  92776. }
  92777. _this._rootMesh.addChild(_this._scaleBoxesParent);
  92778. // Hover color change
  92779. var pointerIds = new Array();
  92780. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92781. if (!pointerIds[pointerInfo.event.pointerId]) {
  92782. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  92783. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  92784. pointerIds[pointerInfo.event.pointerId] = mesh;
  92785. mesh.material = hoverColoredMaterial;
  92786. }
  92787. });
  92788. }
  92789. else {
  92790. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  92791. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  92792. delete pointerIds[pointerInfo.event.pointerId];
  92793. }
  92794. }
  92795. });
  92796. // Update bounding box positions
  92797. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  92798. // Only update the bouding box if scaling has changed
  92799. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  92800. _this.updateBoundingBox();
  92801. }
  92802. });
  92803. _this.updateBoundingBox();
  92804. return _this;
  92805. }
  92806. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  92807. if (value) {
  92808. // Reset anchor mesh to match attached mesh's scale
  92809. // This is needed to avoid invalid box/sphere position on first drag
  92810. this._anchorMesh.addChild(value);
  92811. this._anchorMesh.removeChild(value);
  92812. this.updateBoundingBox();
  92813. }
  92814. };
  92815. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  92816. this._rotateSpheresParent.getChildMeshes()
  92817. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  92818. m.isVisible = (!selectedMesh || m == selectedMesh);
  92819. });
  92820. };
  92821. BoundingBoxGizmo.prototype._recurseComputeWorld = function (node) {
  92822. var _this = this;
  92823. node.computeWorldMatrix(true);
  92824. if (!this.ignoreChildren) {
  92825. node.getDescendants().forEach(function (n) {
  92826. _this._recurseComputeWorld(n);
  92827. });
  92828. }
  92829. };
  92830. /**
  92831. * Updates the bounding box information for the Gizmo
  92832. */
  92833. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  92834. this._update();
  92835. if (this.attachedMesh) {
  92836. // Rotate based on axis
  92837. if (!this.attachedMesh.rotationQuaternion) {
  92838. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  92839. }
  92840. if (!this._anchorMesh.rotationQuaternion) {
  92841. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  92842. }
  92843. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  92844. // Store original position and reset mesh to origin before computing the bounding box
  92845. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  92846. this._tmpVector.copyFrom(this.attachedMesh.position);
  92847. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  92848. this.attachedMesh.position.set(0, 0, 0);
  92849. // Update bounding dimensions/positions
  92850. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  92851. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  92852. // Update gizmo to match bounding box scaling and rotation
  92853. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  92854. 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);
  92855. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  92856. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  92857. this._lineBoundingBox.computeWorldMatrix();
  92858. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  92859. // restore position/rotation values
  92860. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  92861. this.attachedMesh.position.copyFrom(this._tmpVector);
  92862. this._recurseComputeWorld(this.attachedMesh);
  92863. }
  92864. // Update rotation sphere locations
  92865. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  92866. for (var i = 0; i < 3; i++) {
  92867. for (var j = 0; j < 2; j++) {
  92868. for (var k = 0; k < 2; k++) {
  92869. var index = ((i * 4) + (j * 2)) + k;
  92870. if (i == 0) {
  92871. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  92872. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92873. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92874. }
  92875. if (i == 1) {
  92876. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  92877. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92878. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92879. }
  92880. if (i == 2) {
  92881. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  92882. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92883. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92884. }
  92885. if (this.fixedDragMeshScreenSize) {
  92886. this._rootMesh.computeWorldMatrix();
  92887. this._rotateSpheresParent.computeWorldMatrix();
  92888. rotateSpheres[index].computeWorldMatrix();
  92889. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  92890. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  92891. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  92892. }
  92893. else {
  92894. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  92895. }
  92896. }
  92897. }
  92898. }
  92899. // Update scale box locations
  92900. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  92901. for (var i = 0; i < 2; i++) {
  92902. for (var j = 0; j < 2; j++) {
  92903. for (var k = 0; k < 2; k++) {
  92904. var index = ((i * 4) + (j * 2)) + k;
  92905. if (scaleBoxes[index]) {
  92906. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  92907. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92908. if (this.fixedDragMeshScreenSize) {
  92909. this._rootMesh.computeWorldMatrix();
  92910. this._scaleBoxesParent.computeWorldMatrix();
  92911. scaleBoxes[index].computeWorldMatrix();
  92912. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  92913. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  92914. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  92915. }
  92916. else {
  92917. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  92918. }
  92919. }
  92920. }
  92921. }
  92922. }
  92923. if (this.attachedMesh) {
  92924. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  92925. }
  92926. };
  92927. /**
  92928. * Enables rotation on the specified axis and disables rotation on the others
  92929. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  92930. */
  92931. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  92932. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  92933. if (i < 4) {
  92934. m.setEnabled(axis.indexOf("x") != -1);
  92935. }
  92936. else if (i < 8) {
  92937. m.setEnabled(axis.indexOf("y") != -1);
  92938. }
  92939. else {
  92940. m.setEnabled(axis.indexOf("z") != -1);
  92941. }
  92942. });
  92943. };
  92944. /**
  92945. * Disposes of the gizmo
  92946. */
  92947. BoundingBoxGizmo.prototype.dispose = function () {
  92948. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92949. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  92950. this._lineBoundingBox.dispose();
  92951. this._rotateSpheresParent.dispose();
  92952. this._scaleBoxesParent.dispose();
  92953. _super.prototype.dispose.call(this);
  92954. };
  92955. /**
  92956. * 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)
  92957. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  92958. * @returns the bounding box mesh with the passed in mesh as a child
  92959. */
  92960. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  92961. var makeNotPickable = function (root) {
  92962. root.isPickable = false;
  92963. root.getChildMeshes().forEach(function (c) {
  92964. makeNotPickable(c);
  92965. });
  92966. };
  92967. makeNotPickable(mesh);
  92968. // Reset position to get boudning box from origin with no rotation
  92969. if (!mesh.rotationQuaternion) {
  92970. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  92971. }
  92972. var oldPos = mesh.position.clone();
  92973. var oldRot = mesh.rotationQuaternion.clone();
  92974. mesh.rotationQuaternion.set(0, 0, 0, 1);
  92975. mesh.position.set(0, 0, 0);
  92976. // Update bounding dimensions/positions
  92977. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  92978. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  92979. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  92980. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  92981. // Restore original positions
  92982. mesh.addChild(box);
  92983. mesh.rotationQuaternion.copyFrom(oldRot);
  92984. mesh.position.copyFrom(oldPos);
  92985. // Reverse parenting
  92986. mesh.removeChild(box);
  92987. box.addChild(mesh);
  92988. box.visibility = 0;
  92989. return box;
  92990. };
  92991. /**
  92992. * CustomMeshes are not supported by this gizmo
  92993. * @param mesh The mesh to replace the default mesh of the gizmo
  92994. */
  92995. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  92996. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  92997. };
  92998. return BoundingBoxGizmo;
  92999. }(BABYLON.Gizmo));
  93000. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  93001. })(BABYLON || (BABYLON = {}));
  93002. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  93003. var BABYLON;
  93004. (function (BABYLON) {
  93005. /**
  93006. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  93007. */
  93008. var GizmoManager = /** @class */ (function () {
  93009. /**
  93010. * Instatiates a gizmo manager
  93011. * @param scene the scene to overlay the gizmos on top of
  93012. */
  93013. function GizmoManager(scene) {
  93014. var _this = this;
  93015. this.scene = scene;
  93016. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  93017. this._pointerObserver = null;
  93018. this._attachedMesh = null;
  93019. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  93020. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  93021. /**
  93022. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  93023. */
  93024. this.attachableMeshes = null;
  93025. /**
  93026. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  93027. */
  93028. this.usePointerToAttachGizmos = true;
  93029. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  93030. // Instatiate/dispose gizmos based on pointer actions
  93031. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  93032. if (!_this.usePointerToAttachGizmos) {
  93033. return;
  93034. }
  93035. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93036. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  93037. var node = pointerInfo.pickInfo.pickedMesh;
  93038. if (_this.attachableMeshes == null) {
  93039. // Attach to the most parent node
  93040. while (node && node.parent != null) {
  93041. node = node.parent;
  93042. }
  93043. }
  93044. else {
  93045. // Attach to the parent node that is an attachableMesh
  93046. var found = false;
  93047. _this.attachableMeshes.forEach(function (mesh) {
  93048. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  93049. node = mesh;
  93050. found = true;
  93051. }
  93052. });
  93053. if (!found) {
  93054. node = null;
  93055. }
  93056. }
  93057. if (node instanceof BABYLON.AbstractMesh) {
  93058. _this.attachToMesh(node);
  93059. }
  93060. else {
  93061. _this.attachToMesh(null);
  93062. }
  93063. }
  93064. else {
  93065. _this.attachToMesh(null);
  93066. }
  93067. }
  93068. });
  93069. }
  93070. /**
  93071. * Attaches a set of gizmos to the specified mesh
  93072. * @param mesh The mesh the gizmo's should be attached to
  93073. */
  93074. GizmoManager.prototype.attachToMesh = function (mesh) {
  93075. if (this._attachedMesh) {
  93076. this._attachedMesh.removeBehavior(this._dragBehavior);
  93077. }
  93078. this._attachedMesh = mesh;
  93079. for (var key in this.gizmos) {
  93080. var gizmo = (this.gizmos[key]);
  93081. if (gizmo && this._gizmosEnabled[key]) {
  93082. gizmo.attachedMesh = mesh;
  93083. }
  93084. }
  93085. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  93086. this._attachedMesh.addBehavior(this._dragBehavior);
  93087. }
  93088. };
  93089. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  93090. get: function () {
  93091. return this._gizmosEnabled.positionGizmo;
  93092. },
  93093. /**
  93094. * If the position gizmo is enabled
  93095. */
  93096. set: function (value) {
  93097. if (value) {
  93098. if (!this.gizmos.positionGizmo) {
  93099. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  93100. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93101. }
  93102. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  93103. }
  93104. else if (this.gizmos.positionGizmo) {
  93105. this.gizmos.positionGizmo.attachedMesh = null;
  93106. }
  93107. this._gizmosEnabled.positionGizmo = value;
  93108. },
  93109. enumerable: true,
  93110. configurable: true
  93111. });
  93112. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  93113. get: function () {
  93114. return this._gizmosEnabled.rotationGizmo;
  93115. },
  93116. /**
  93117. * If the rotation gizmo is enabled
  93118. */
  93119. set: function (value) {
  93120. if (value) {
  93121. if (!this.gizmos.rotationGizmo) {
  93122. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  93123. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93124. }
  93125. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  93126. }
  93127. else if (this.gizmos.rotationGizmo) {
  93128. this.gizmos.rotationGizmo.attachedMesh = null;
  93129. }
  93130. this._gizmosEnabled.rotationGizmo = value;
  93131. },
  93132. enumerable: true,
  93133. configurable: true
  93134. });
  93135. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  93136. get: function () {
  93137. return this._gizmosEnabled.scaleGizmo;
  93138. },
  93139. /**
  93140. * If the scale gizmo is enabled
  93141. */
  93142. set: function (value) {
  93143. if (value) {
  93144. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  93145. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  93146. }
  93147. else if (this.gizmos.scaleGizmo) {
  93148. this.gizmos.scaleGizmo.attachedMesh = null;
  93149. }
  93150. this._gizmosEnabled.scaleGizmo = value;
  93151. },
  93152. enumerable: true,
  93153. configurable: true
  93154. });
  93155. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  93156. get: function () {
  93157. return this._gizmosEnabled.boundingBoxGizmo;
  93158. },
  93159. /**
  93160. * If the boundingBox gizmo is enabled
  93161. */
  93162. set: function (value) {
  93163. if (value) {
  93164. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  93165. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  93166. if (this._attachedMesh) {
  93167. this._attachedMesh.removeBehavior(this._dragBehavior);
  93168. this._attachedMesh.addBehavior(this._dragBehavior);
  93169. }
  93170. }
  93171. else if (this.gizmos.boundingBoxGizmo) {
  93172. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  93173. }
  93174. this._gizmosEnabled.boundingBoxGizmo = value;
  93175. },
  93176. enumerable: true,
  93177. configurable: true
  93178. });
  93179. /**
  93180. * Disposes of the gizmo manager
  93181. */
  93182. GizmoManager.prototype.dispose = function () {
  93183. this.scene.onPointerObservable.remove(this._pointerObserver);
  93184. for (var key in this.gizmos) {
  93185. var gizmo = (this.gizmos[key]);
  93186. if (gizmo) {
  93187. gizmo.dispose();
  93188. }
  93189. }
  93190. this._dragBehavior.detach();
  93191. };
  93192. return GizmoManager;
  93193. }());
  93194. BABYLON.GizmoManager = GizmoManager;
  93195. })(BABYLON || (BABYLON = {}));
  93196. //# sourceMappingURL=babylon.gizmoManager.js.map
  93197. var BABYLON;
  93198. (function (BABYLON) {
  93199. /**
  93200. * Defines a target to use with MorphTargetManager
  93201. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93202. */
  93203. var MorphTarget = /** @class */ (function () {
  93204. /**
  93205. * Creates a new MorphTarget
  93206. * @param name defines the name of the target
  93207. * @param influence defines the influence to use
  93208. */
  93209. function MorphTarget(
  93210. /** defines the name of the target */
  93211. name, influence, scene) {
  93212. if (influence === void 0) { influence = 0; }
  93213. if (scene === void 0) { scene = null; }
  93214. this.name = name;
  93215. /**
  93216. * Gets or sets the list of animations
  93217. */
  93218. this.animations = new Array();
  93219. this._positions = null;
  93220. this._normals = null;
  93221. this._tangents = null;
  93222. /**
  93223. * Observable raised when the influence changes
  93224. */
  93225. this.onInfluenceChanged = new BABYLON.Observable();
  93226. this._animationPropertiesOverride = null;
  93227. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93228. this.influence = influence;
  93229. }
  93230. Object.defineProperty(MorphTarget.prototype, "influence", {
  93231. /**
  93232. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  93233. */
  93234. get: function () {
  93235. return this._influence;
  93236. },
  93237. set: function (influence) {
  93238. if (this._influence === influence) {
  93239. return;
  93240. }
  93241. var previous = this._influence;
  93242. this._influence = influence;
  93243. if (this.onInfluenceChanged.hasObservers) {
  93244. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  93245. }
  93246. },
  93247. enumerable: true,
  93248. configurable: true
  93249. });
  93250. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  93251. /**
  93252. * Gets or sets the animation properties override
  93253. */
  93254. get: function () {
  93255. if (!this._animationPropertiesOverride && this._scene) {
  93256. return this._scene.animationPropertiesOverride;
  93257. }
  93258. return this._animationPropertiesOverride;
  93259. },
  93260. set: function (value) {
  93261. this._animationPropertiesOverride = value;
  93262. },
  93263. enumerable: true,
  93264. configurable: true
  93265. });
  93266. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  93267. /**
  93268. * Gets a boolean defining if the target contains position data
  93269. */
  93270. get: function () {
  93271. return !!this._positions;
  93272. },
  93273. enumerable: true,
  93274. configurable: true
  93275. });
  93276. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  93277. /**
  93278. * Gets a boolean defining if the target contains normal data
  93279. */
  93280. get: function () {
  93281. return !!this._normals;
  93282. },
  93283. enumerable: true,
  93284. configurable: true
  93285. });
  93286. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  93287. /**
  93288. * Gets a boolean defining if the target contains tangent data
  93289. */
  93290. get: function () {
  93291. return !!this._tangents;
  93292. },
  93293. enumerable: true,
  93294. configurable: true
  93295. });
  93296. /**
  93297. * Affects position data to this target
  93298. * @param data defines the position data to use
  93299. */
  93300. MorphTarget.prototype.setPositions = function (data) {
  93301. this._positions = data;
  93302. };
  93303. /**
  93304. * Gets the position data stored in this target
  93305. * @returns a FloatArray containing the position data (or null if not present)
  93306. */
  93307. MorphTarget.prototype.getPositions = function () {
  93308. return this._positions;
  93309. };
  93310. /**
  93311. * Affects normal data to this target
  93312. * @param data defines the normal data to use
  93313. */
  93314. MorphTarget.prototype.setNormals = function (data) {
  93315. this._normals = data;
  93316. };
  93317. /**
  93318. * Gets the normal data stored in this target
  93319. * @returns a FloatArray containing the normal data (or null if not present)
  93320. */
  93321. MorphTarget.prototype.getNormals = function () {
  93322. return this._normals;
  93323. };
  93324. /**
  93325. * Affects tangent data to this target
  93326. * @param data defines the tangent data to use
  93327. */
  93328. MorphTarget.prototype.setTangents = function (data) {
  93329. this._tangents = data;
  93330. };
  93331. /**
  93332. * Gets the tangent data stored in this target
  93333. * @returns a FloatArray containing the tangent data (or null if not present)
  93334. */
  93335. MorphTarget.prototype.getTangents = function () {
  93336. return this._tangents;
  93337. };
  93338. /**
  93339. * Serializes the current target into a Serialization object
  93340. * @returns the serialized object
  93341. */
  93342. MorphTarget.prototype.serialize = function () {
  93343. var serializationObject = {};
  93344. serializationObject.name = this.name;
  93345. serializationObject.influence = this.influence;
  93346. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93347. if (this.hasNormals) {
  93348. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93349. }
  93350. if (this.hasTangents) {
  93351. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93352. }
  93353. // Animations
  93354. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93355. return serializationObject;
  93356. };
  93357. // Statics
  93358. /**
  93359. * Creates a new target from serialized data
  93360. * @param serializationObject defines the serialized data to use
  93361. * @returns a new MorphTarget
  93362. */
  93363. MorphTarget.Parse = function (serializationObject) {
  93364. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93365. result.setPositions(serializationObject.positions);
  93366. if (serializationObject.normals) {
  93367. result.setNormals(serializationObject.normals);
  93368. }
  93369. if (serializationObject.tangents) {
  93370. result.setTangents(serializationObject.tangents);
  93371. }
  93372. // Animations
  93373. if (serializationObject.animations) {
  93374. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93375. var parsedAnimation = serializationObject.animations[animationIndex];
  93376. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93377. }
  93378. }
  93379. return result;
  93380. };
  93381. /**
  93382. * Creates a MorphTarget from mesh data
  93383. * @param mesh defines the source mesh
  93384. * @param name defines the name to use for the new target
  93385. * @param influence defines the influence to attach to the target
  93386. * @returns a new MorphTarget
  93387. */
  93388. MorphTarget.FromMesh = function (mesh, name, influence) {
  93389. if (!name) {
  93390. name = mesh.name;
  93391. }
  93392. var result = new MorphTarget(name, influence, mesh.getScene());
  93393. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93394. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93395. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93396. }
  93397. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93398. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93399. }
  93400. return result;
  93401. };
  93402. return MorphTarget;
  93403. }());
  93404. BABYLON.MorphTarget = MorphTarget;
  93405. })(BABYLON || (BABYLON = {}));
  93406. //# sourceMappingURL=babylon.morphTarget.js.map
  93407. var BABYLON;
  93408. (function (BABYLON) {
  93409. /**
  93410. * This class is used to deform meshes using morphing between different targets
  93411. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93412. */
  93413. var MorphTargetManager = /** @class */ (function () {
  93414. /**
  93415. * Creates a new MorphTargetManager
  93416. * @param scene defines the current scene
  93417. */
  93418. function MorphTargetManager(scene) {
  93419. if (scene === void 0) { scene = null; }
  93420. this._targets = new Array();
  93421. this._targetObservable = new Array();
  93422. this._activeTargets = new BABYLON.SmartArray(16);
  93423. this._supportsNormals = false;
  93424. this._supportsTangents = false;
  93425. this._vertexCount = 0;
  93426. this._uniqueId = 0;
  93427. this._tempInfluences = new Array();
  93428. if (!scene) {
  93429. scene = BABYLON.Engine.LastCreatedScene;
  93430. }
  93431. this._scene = scene;
  93432. if (this._scene) {
  93433. this._scene.morphTargetManagers.push(this);
  93434. this._uniqueId = this._scene.getUniqueId();
  93435. }
  93436. }
  93437. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  93438. /**
  93439. * Gets the unique ID of this manager
  93440. */
  93441. get: function () {
  93442. return this._uniqueId;
  93443. },
  93444. enumerable: true,
  93445. configurable: true
  93446. });
  93447. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  93448. /**
  93449. * Gets the number of vertices handled by this manager
  93450. */
  93451. get: function () {
  93452. return this._vertexCount;
  93453. },
  93454. enumerable: true,
  93455. configurable: true
  93456. });
  93457. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  93458. /**
  93459. * Gets a boolean indicating if this manager supports morphing of normals
  93460. */
  93461. get: function () {
  93462. return this._supportsNormals;
  93463. },
  93464. enumerable: true,
  93465. configurable: true
  93466. });
  93467. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  93468. /**
  93469. * Gets a boolean indicating if this manager supports morphing of tangents
  93470. */
  93471. get: function () {
  93472. return this._supportsTangents;
  93473. },
  93474. enumerable: true,
  93475. configurable: true
  93476. });
  93477. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  93478. /**
  93479. * Gets the number of targets stored in this manager
  93480. */
  93481. get: function () {
  93482. return this._targets.length;
  93483. },
  93484. enumerable: true,
  93485. configurable: true
  93486. });
  93487. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  93488. /**
  93489. * Gets the number of influencers (ie. the number of targets with influences > 0)
  93490. */
  93491. get: function () {
  93492. return this._activeTargets.length;
  93493. },
  93494. enumerable: true,
  93495. configurable: true
  93496. });
  93497. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  93498. /**
  93499. * Gets the list of influences (one per target)
  93500. */
  93501. get: function () {
  93502. return this._influences;
  93503. },
  93504. enumerable: true,
  93505. configurable: true
  93506. });
  93507. /**
  93508. * Gets the active target at specified index. An active target is a target with an influence > 0
  93509. * @param index defines the index to check
  93510. * @returns the requested target
  93511. */
  93512. MorphTargetManager.prototype.getActiveTarget = function (index) {
  93513. return this._activeTargets.data[index];
  93514. };
  93515. /**
  93516. * Gets the target at specified index
  93517. * @param index defines the index to check
  93518. * @returns the requested target
  93519. */
  93520. MorphTargetManager.prototype.getTarget = function (index) {
  93521. return this._targets[index];
  93522. };
  93523. /**
  93524. * Add a new target to this manager
  93525. * @param target defines the target to add
  93526. */
  93527. MorphTargetManager.prototype.addTarget = function (target) {
  93528. var _this = this;
  93529. this._targets.push(target);
  93530. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  93531. _this._syncActiveTargets(needUpdate);
  93532. }));
  93533. this._syncActiveTargets(true);
  93534. };
  93535. /**
  93536. * Removes a target from the manager
  93537. * @param target defines the target to remove
  93538. */
  93539. MorphTargetManager.prototype.removeTarget = function (target) {
  93540. var index = this._targets.indexOf(target);
  93541. if (index >= 0) {
  93542. this._targets.splice(index, 1);
  93543. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  93544. this._syncActiveTargets(true);
  93545. }
  93546. };
  93547. /**
  93548. * Serializes the current manager into a Serialization object
  93549. * @returns the serialized object
  93550. */
  93551. MorphTargetManager.prototype.serialize = function () {
  93552. var serializationObject = {};
  93553. serializationObject.id = this.uniqueId;
  93554. serializationObject.targets = [];
  93555. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93556. var target = _a[_i];
  93557. serializationObject.targets.push(target.serialize());
  93558. }
  93559. return serializationObject;
  93560. };
  93561. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  93562. var influenceCount = 0;
  93563. this._activeTargets.reset();
  93564. this._supportsNormals = true;
  93565. this._supportsTangents = true;
  93566. this._vertexCount = 0;
  93567. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93568. var target = _a[_i];
  93569. this._activeTargets.push(target);
  93570. this._tempInfluences[influenceCount++] = target.influence;
  93571. var positions = target.getPositions();
  93572. if (positions) {
  93573. this._supportsNormals = this._supportsNormals && target.hasNormals;
  93574. this._supportsTangents = this._supportsTangents && target.hasTangents;
  93575. var vertexCount = positions.length / 3;
  93576. if (this._vertexCount === 0) {
  93577. this._vertexCount = vertexCount;
  93578. }
  93579. else if (this._vertexCount !== vertexCount) {
  93580. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  93581. return;
  93582. }
  93583. }
  93584. }
  93585. if (!this._influences || this._influences.length !== influenceCount) {
  93586. this._influences = new Float32Array(influenceCount);
  93587. }
  93588. for (var index = 0; index < influenceCount; index++) {
  93589. this._influences[index] = this._tempInfluences[index];
  93590. }
  93591. if (needUpdate) {
  93592. this.synchronize();
  93593. }
  93594. };
  93595. /**
  93596. * Syncrhonize the targets with all the meshes using this morph target manager
  93597. */
  93598. MorphTargetManager.prototype.synchronize = function () {
  93599. if (!this._scene) {
  93600. return;
  93601. }
  93602. // Flag meshes as dirty to resync with the active targets
  93603. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  93604. var mesh = _a[_i];
  93605. if (mesh.morphTargetManager === this) {
  93606. mesh._syncGeometryWithMorphTargetManager();
  93607. }
  93608. }
  93609. };
  93610. // Statics
  93611. /**
  93612. * Creates a new MorphTargetManager from serialized data
  93613. * @param serializationObject defines the serialized data
  93614. * @param scene defines the hosting scene
  93615. * @returns the new MorphTargetManager
  93616. */
  93617. MorphTargetManager.Parse = function (serializationObject, scene) {
  93618. var result = new MorphTargetManager(scene);
  93619. result._uniqueId = serializationObject.id;
  93620. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  93621. var targetData = _a[_i];
  93622. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  93623. }
  93624. return result;
  93625. };
  93626. return MorphTargetManager;
  93627. }());
  93628. BABYLON.MorphTargetManager = MorphTargetManager;
  93629. })(BABYLON || (BABYLON = {}));
  93630. //# sourceMappingURL=babylon.morphTargetManager.js.map
  93631. var BABYLON;
  93632. (function (BABYLON) {
  93633. var Octree = /** @class */ (function () {
  93634. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  93635. if (maxDepth === void 0) { maxDepth = 2; }
  93636. this.maxDepth = maxDepth;
  93637. this.dynamicContent = new Array();
  93638. this._maxBlockCapacity = maxBlockCapacity || 64;
  93639. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  93640. this._creationFunc = creationFunc;
  93641. }
  93642. // Methods
  93643. Octree.prototype.update = function (worldMin, worldMax, entries) {
  93644. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  93645. };
  93646. Octree.prototype.addMesh = function (entry) {
  93647. for (var index = 0; index < this.blocks.length; index++) {
  93648. var block = this.blocks[index];
  93649. block.addEntry(entry);
  93650. }
  93651. };
  93652. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  93653. this._selectionContent.reset();
  93654. for (var index = 0; index < this.blocks.length; index++) {
  93655. var block = this.blocks[index];
  93656. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  93657. }
  93658. if (allowDuplicate) {
  93659. this._selectionContent.concat(this.dynamicContent);
  93660. }
  93661. else {
  93662. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93663. }
  93664. return this._selectionContent;
  93665. };
  93666. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  93667. this._selectionContent.reset();
  93668. for (var index = 0; index < this.blocks.length; index++) {
  93669. var block = this.blocks[index];
  93670. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  93671. }
  93672. if (allowDuplicate) {
  93673. this._selectionContent.concat(this.dynamicContent);
  93674. }
  93675. else {
  93676. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93677. }
  93678. return this._selectionContent;
  93679. };
  93680. Octree.prototype.intersectsRay = function (ray) {
  93681. this._selectionContent.reset();
  93682. for (var index = 0; index < this.blocks.length; index++) {
  93683. var block = this.blocks[index];
  93684. block.intersectsRay(ray, this._selectionContent);
  93685. }
  93686. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93687. return this._selectionContent;
  93688. };
  93689. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  93690. target.blocks = new Array();
  93691. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  93692. // Segmenting space
  93693. for (var x = 0; x < 2; x++) {
  93694. for (var y = 0; y < 2; y++) {
  93695. for (var z = 0; z < 2; z++) {
  93696. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  93697. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  93698. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  93699. block.addEntries(entries);
  93700. target.blocks.push(block);
  93701. }
  93702. }
  93703. }
  93704. };
  93705. Octree.CreationFuncForMeshes = function (entry, block) {
  93706. var boundingInfo = entry.getBoundingInfo();
  93707. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  93708. block.entries.push(entry);
  93709. }
  93710. };
  93711. Octree.CreationFuncForSubMeshes = function (entry, block) {
  93712. var boundingInfo = entry.getBoundingInfo();
  93713. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  93714. block.entries.push(entry);
  93715. }
  93716. };
  93717. return Octree;
  93718. }());
  93719. BABYLON.Octree = Octree;
  93720. })(BABYLON || (BABYLON = {}));
  93721. //# sourceMappingURL=babylon.octree.js.map
  93722. var BABYLON;
  93723. (function (BABYLON) {
  93724. var OctreeBlock = /** @class */ (function () {
  93725. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  93726. this.entries = new Array();
  93727. this._boundingVectors = new Array();
  93728. this._capacity = capacity;
  93729. this._depth = depth;
  93730. this._maxDepth = maxDepth;
  93731. this._creationFunc = creationFunc;
  93732. this._minPoint = minPoint;
  93733. this._maxPoint = maxPoint;
  93734. this._boundingVectors.push(minPoint.clone());
  93735. this._boundingVectors.push(maxPoint.clone());
  93736. this._boundingVectors.push(minPoint.clone());
  93737. this._boundingVectors[2].x = maxPoint.x;
  93738. this._boundingVectors.push(minPoint.clone());
  93739. this._boundingVectors[3].y = maxPoint.y;
  93740. this._boundingVectors.push(minPoint.clone());
  93741. this._boundingVectors[4].z = maxPoint.z;
  93742. this._boundingVectors.push(maxPoint.clone());
  93743. this._boundingVectors[5].z = minPoint.z;
  93744. this._boundingVectors.push(maxPoint.clone());
  93745. this._boundingVectors[6].x = minPoint.x;
  93746. this._boundingVectors.push(maxPoint.clone());
  93747. this._boundingVectors[7].y = minPoint.y;
  93748. }
  93749. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  93750. // Property
  93751. get: function () {
  93752. return this._capacity;
  93753. },
  93754. enumerable: true,
  93755. configurable: true
  93756. });
  93757. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  93758. get: function () {
  93759. return this._minPoint;
  93760. },
  93761. enumerable: true,
  93762. configurable: true
  93763. });
  93764. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  93765. get: function () {
  93766. return this._maxPoint;
  93767. },
  93768. enumerable: true,
  93769. configurable: true
  93770. });
  93771. // Methods
  93772. OctreeBlock.prototype.addEntry = function (entry) {
  93773. if (this.blocks) {
  93774. for (var index = 0; index < this.blocks.length; index++) {
  93775. var block = this.blocks[index];
  93776. block.addEntry(entry);
  93777. }
  93778. return;
  93779. }
  93780. this._creationFunc(entry, this);
  93781. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  93782. this.createInnerBlocks();
  93783. }
  93784. };
  93785. OctreeBlock.prototype.addEntries = function (entries) {
  93786. for (var index = 0; index < entries.length; index++) {
  93787. var mesh = entries[index];
  93788. this.addEntry(mesh);
  93789. }
  93790. };
  93791. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  93792. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  93793. if (this.blocks) {
  93794. for (var index = 0; index < this.blocks.length; index++) {
  93795. var block = this.blocks[index];
  93796. block.select(frustumPlanes, selection, allowDuplicate);
  93797. }
  93798. return;
  93799. }
  93800. if (allowDuplicate) {
  93801. selection.concat(this.entries);
  93802. }
  93803. else {
  93804. selection.concatWithNoDuplicate(this.entries);
  93805. }
  93806. }
  93807. };
  93808. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  93809. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  93810. if (this.blocks) {
  93811. for (var index = 0; index < this.blocks.length; index++) {
  93812. var block = this.blocks[index];
  93813. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  93814. }
  93815. return;
  93816. }
  93817. if (allowDuplicate) {
  93818. selection.concat(this.entries);
  93819. }
  93820. else {
  93821. selection.concatWithNoDuplicate(this.entries);
  93822. }
  93823. }
  93824. };
  93825. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  93826. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  93827. if (this.blocks) {
  93828. for (var index = 0; index < this.blocks.length; index++) {
  93829. var block = this.blocks[index];
  93830. block.intersectsRay(ray, selection);
  93831. }
  93832. return;
  93833. }
  93834. selection.concatWithNoDuplicate(this.entries);
  93835. }
  93836. };
  93837. OctreeBlock.prototype.createInnerBlocks = function () {
  93838. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  93839. };
  93840. return OctreeBlock;
  93841. }());
  93842. BABYLON.OctreeBlock = OctreeBlock;
  93843. })(BABYLON || (BABYLON = {}));
  93844. //# sourceMappingURL=babylon.octreeBlock.js.map
  93845. var BABYLON;
  93846. (function (BABYLON) {
  93847. /**
  93848. * Postprocess used to generate anaglyphic rendering
  93849. */
  93850. var AnaglyphPostProcess = /** @class */ (function (_super) {
  93851. __extends(AnaglyphPostProcess, _super);
  93852. /**
  93853. * Creates a new AnaglyphPostProcess
  93854. * @param name defines postprocess name
  93855. * @param options defines creation options or target ratio scale
  93856. * @param rigCameras defines cameras using this postprocess
  93857. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  93858. * @param engine defines hosting engine
  93859. * @param reusable defines if the postprocess will be reused multiple times per frame
  93860. */
  93861. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  93862. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  93863. _this._passedProcess = rigCameras[0]._rigPostProcess;
  93864. _this.onApplyObservable.add(function (effect) {
  93865. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  93866. });
  93867. return _this;
  93868. }
  93869. return AnaglyphPostProcess;
  93870. }(BABYLON.PostProcess));
  93871. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  93872. })(BABYLON || (BABYLON = {}));
  93873. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  93874. var BABYLON;
  93875. (function (BABYLON) {
  93876. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  93877. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93878. });
  93879. /**
  93880. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  93881. */
  93882. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  93883. __extends(AnaglyphArcRotateCamera, _super);
  93884. /**
  93885. * Creates a new AnaglyphArcRotateCamera
  93886. * @param name defines camera name
  93887. * @param alpha defines alpha angle (in radians)
  93888. * @param beta defines beta angle (in radians)
  93889. * @param radius defines radius
  93890. * @param target defines camera target
  93891. * @param interaxialDistance defines distance between each color axis
  93892. * @param scene defines the hosting scene
  93893. */
  93894. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  93895. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93896. _this.interaxialDistance = interaxialDistance;
  93897. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93898. return _this;
  93899. }
  93900. /**
  93901. * Gets camera class name
  93902. * @returns AnaglyphArcRotateCamera
  93903. */
  93904. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  93905. return "AnaglyphArcRotateCamera";
  93906. };
  93907. return AnaglyphArcRotateCamera;
  93908. }(BABYLON.ArcRotateCamera));
  93909. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  93910. })(BABYLON || (BABYLON = {}));
  93911. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  93912. var BABYLON;
  93913. (function (BABYLON) {
  93914. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  93915. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93916. });
  93917. /**
  93918. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  93919. */
  93920. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  93921. __extends(AnaglyphFreeCamera, _super);
  93922. /**
  93923. * Creates a new AnaglyphFreeCamera
  93924. * @param name defines camera name
  93925. * @param position defines initial position
  93926. * @param interaxialDistance defines distance between each color axis
  93927. * @param scene defines the hosting scene
  93928. */
  93929. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  93930. var _this = _super.call(this, name, position, scene) || this;
  93931. _this.interaxialDistance = interaxialDistance;
  93932. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93933. return _this;
  93934. }
  93935. /**
  93936. * Gets camera class name
  93937. * @returns AnaglyphFreeCamera
  93938. */
  93939. AnaglyphFreeCamera.prototype.getClassName = function () {
  93940. return "AnaglyphFreeCamera";
  93941. };
  93942. return AnaglyphFreeCamera;
  93943. }(BABYLON.FreeCamera));
  93944. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  93945. })(BABYLON || (BABYLON = {}));
  93946. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  93947. var BABYLON;
  93948. (function (BABYLON) {
  93949. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  93950. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93951. });
  93952. /**
  93953. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  93954. */
  93955. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  93956. __extends(AnaglyphGamepadCamera, _super);
  93957. /**
  93958. * Creates a new AnaglyphGamepadCamera
  93959. * @param name defines camera name
  93960. * @param position defines initial position
  93961. * @param interaxialDistance defines distance between each color axis
  93962. * @param scene defines the hosting scene
  93963. */
  93964. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  93965. var _this = _super.call(this, name, position, scene) || this;
  93966. _this.interaxialDistance = interaxialDistance;
  93967. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93968. return _this;
  93969. }
  93970. /**
  93971. * Gets camera class name
  93972. * @returns AnaglyphGamepadCamera
  93973. */
  93974. AnaglyphGamepadCamera.prototype.getClassName = function () {
  93975. return "AnaglyphGamepadCamera";
  93976. };
  93977. return AnaglyphGamepadCamera;
  93978. }(BABYLON.GamepadCamera));
  93979. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  93980. })(BABYLON || (BABYLON = {}));
  93981. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  93982. var BABYLON;
  93983. (function (BABYLON) {
  93984. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  93985. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93986. });
  93987. /**
  93988. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  93989. */
  93990. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  93991. __extends(AnaglyphUniversalCamera, _super);
  93992. /**
  93993. * Creates a new AnaglyphUniversalCamera
  93994. * @param name defines camera name
  93995. * @param position defines initial position
  93996. * @param interaxialDistance defines distance between each color axis
  93997. * @param scene defines the hosting scene
  93998. */
  93999. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  94000. var _this = _super.call(this, name, position, scene) || this;
  94001. _this.interaxialDistance = interaxialDistance;
  94002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94003. return _this;
  94004. }
  94005. /**
  94006. * Gets camera class name
  94007. * @returns AnaglyphUniversalCamera
  94008. */
  94009. AnaglyphUniversalCamera.prototype.getClassName = function () {
  94010. return "AnaglyphUniversalCamera";
  94011. };
  94012. return AnaglyphUniversalCamera;
  94013. }(BABYLON.UniversalCamera));
  94014. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  94015. })(BABYLON || (BABYLON = {}));
  94016. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  94017. var BABYLON;
  94018. (function (BABYLON) {
  94019. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  94020. __extends(StereoscopicInterlacePostProcess, _super);
  94021. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  94022. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  94023. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94024. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94025. _this.onSizeChangedObservable.add(function () {
  94026. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94027. });
  94028. _this.onApplyObservable.add(function (effect) {
  94029. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  94030. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  94031. });
  94032. return _this;
  94033. }
  94034. return StereoscopicInterlacePostProcess;
  94035. }(BABYLON.PostProcess));
  94036. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  94037. })(BABYLON || (BABYLON = {}));
  94038. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  94039. var BABYLON;
  94040. (function (BABYLON) {
  94041. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  94042. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94043. });
  94044. /**
  94045. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  94046. */
  94047. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  94048. __extends(StereoscopicArcRotateCamera, _super);
  94049. /**
  94050. * Creates a new StereoscopicArcRotateCamera
  94051. * @param name defines camera name
  94052. * @param alpha defines alpha angle (in radians)
  94053. * @param beta defines beta angle (in radians)
  94054. * @param radius defines radius
  94055. * @param target defines camera target
  94056. * @param interaxialDistance defines distance between each color axis
  94057. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94058. * @param scene defines the hosting scene
  94059. */
  94060. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  94061. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94062. _this.interaxialDistance = interaxialDistance;
  94063. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94064. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94065. return _this;
  94066. }
  94067. /**
  94068. * Gets camera class name
  94069. * @returns StereoscopicArcRotateCamera
  94070. */
  94071. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  94072. return "StereoscopicArcRotateCamera";
  94073. };
  94074. return StereoscopicArcRotateCamera;
  94075. }(BABYLON.ArcRotateCamera));
  94076. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  94077. })(BABYLON || (BABYLON = {}));
  94078. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  94079. var BABYLON;
  94080. (function (BABYLON) {
  94081. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94082. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94083. });
  94084. /**
  94085. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  94086. */
  94087. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  94088. __extends(StereoscopicFreeCamera, _super);
  94089. /**
  94090. * Creates a new StereoscopicFreeCamera
  94091. * @param name defines camera name
  94092. * @param position defines initial position
  94093. * @param interaxialDistance defines distance between each color axis
  94094. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94095. * @param scene defines the hosting scene
  94096. */
  94097. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94098. var _this = _super.call(this, name, position, scene) || this;
  94099. _this.interaxialDistance = interaxialDistance;
  94100. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94101. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94102. return _this;
  94103. }
  94104. /**
  94105. * Gets camera class name
  94106. * @returns StereoscopicFreeCamera
  94107. */
  94108. StereoscopicFreeCamera.prototype.getClassName = function () {
  94109. return "StereoscopicFreeCamera";
  94110. };
  94111. return StereoscopicFreeCamera;
  94112. }(BABYLON.FreeCamera));
  94113. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  94114. })(BABYLON || (BABYLON = {}));
  94115. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  94116. var BABYLON;
  94117. (function (BABYLON) {
  94118. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  94119. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94120. });
  94121. /**
  94122. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  94123. */
  94124. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  94125. __extends(StereoscopicGamepadCamera, _super);
  94126. /**
  94127. * Creates a new StereoscopicGamepadCamera
  94128. * @param name defines camera name
  94129. * @param position defines initial position
  94130. * @param interaxialDistance defines distance between each color axis
  94131. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94132. * @param scene defines the hosting scene
  94133. */
  94134. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94135. var _this = _super.call(this, name, position, scene) || this;
  94136. _this.interaxialDistance = interaxialDistance;
  94137. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94138. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94139. return _this;
  94140. }
  94141. /**
  94142. * Gets camera class name
  94143. * @returns StereoscopicGamepadCamera
  94144. */
  94145. StereoscopicGamepadCamera.prototype.getClassName = function () {
  94146. return "StereoscopicGamepadCamera";
  94147. };
  94148. return StereoscopicGamepadCamera;
  94149. }(BABYLON.GamepadCamera));
  94150. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  94151. })(BABYLON || (BABYLON = {}));
  94152. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  94153. var BABYLON;
  94154. (function (BABYLON) {
  94155. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94156. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94157. });
  94158. /**
  94159. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  94160. */
  94161. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  94162. __extends(StereoscopicUniversalCamera, _super);
  94163. /**
  94164. * Creates a new StereoscopicUniversalCamera
  94165. * @param name defines camera name
  94166. * @param position defines initial position
  94167. * @param interaxialDistance defines distance between each color axis
  94168. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94169. * @param scene defines the hosting scene
  94170. */
  94171. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94172. var _this = _super.call(this, name, position, scene) || this;
  94173. _this.interaxialDistance = interaxialDistance;
  94174. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94175. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94176. return _this;
  94177. }
  94178. /**
  94179. * Gets camera class name
  94180. * @returns StereoscopicUniversalCamera
  94181. */
  94182. StereoscopicUniversalCamera.prototype.getClassName = function () {
  94183. return "StereoscopicUniversalCamera";
  94184. };
  94185. return StereoscopicUniversalCamera;
  94186. }(BABYLON.UniversalCamera));
  94187. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  94188. })(BABYLON || (BABYLON = {}));
  94189. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  94190. var BABYLON;
  94191. (function (BABYLON) {
  94192. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  94193. __extends(VRDistortionCorrectionPostProcess, _super);
  94194. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  94195. var _this = _super.call(this, name, "vrDistortionCorrection", [
  94196. 'LensCenter',
  94197. 'Scale',
  94198. 'ScaleIn',
  94199. 'HmdWarpParam'
  94200. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  94201. _this._isRightEye = isRightEye;
  94202. _this._distortionFactors = vrMetrics.distortionK;
  94203. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  94204. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  94205. _this.adaptScaleToCurrentViewport = true;
  94206. _this.onSizeChangedObservable.add(function () {
  94207. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  94208. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  94209. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  94210. });
  94211. _this.onApplyObservable.add(function (effect) {
  94212. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  94213. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  94214. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  94215. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  94216. });
  94217. return _this;
  94218. }
  94219. return VRDistortionCorrectionPostProcess;
  94220. }(BABYLON.PostProcess));
  94221. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  94222. })(BABYLON || (BABYLON = {}));
  94223. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  94224. var BABYLON;
  94225. (function (BABYLON) {
  94226. /**
  94227. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  94228. * Screen rotation is taken into account.
  94229. */
  94230. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  94231. function FreeCameraDeviceOrientationInput() {
  94232. var _this = this;
  94233. this._screenOrientationAngle = 0;
  94234. this._screenQuaternion = new BABYLON.Quaternion();
  94235. this._alpha = 0;
  94236. this._beta = 0;
  94237. this._gamma = 0;
  94238. this._orientationChanged = function () {
  94239. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  94240. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  94241. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  94242. };
  94243. this._deviceOrientation = function (evt) {
  94244. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  94245. _this._beta = evt.beta !== null ? evt.beta : 0;
  94246. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  94247. };
  94248. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  94249. this._orientationChanged();
  94250. }
  94251. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  94252. get: function () {
  94253. return this._camera;
  94254. },
  94255. set: function (camera) {
  94256. this._camera = camera;
  94257. if (this._camera != null && !this._camera.rotationQuaternion) {
  94258. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  94259. }
  94260. },
  94261. enumerable: true,
  94262. configurable: true
  94263. });
  94264. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94265. window.addEventListener("orientationchange", this._orientationChanged);
  94266. window.addEventListener("deviceorientation", this._deviceOrientation);
  94267. //In certain cases, the attach control is called AFTER orientation was changed,
  94268. //So this is needed.
  94269. this._orientationChanged();
  94270. };
  94271. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  94272. window.removeEventListener("orientationchange", this._orientationChanged);
  94273. window.removeEventListener("deviceorientation", this._deviceOrientation);
  94274. };
  94275. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  94276. //if no device orientation provided, don't update the rotation.
  94277. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  94278. if (!this._alpha)
  94279. return;
  94280. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  94281. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  94282. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  94283. //Mirror on XY Plane
  94284. this._camera.rotationQuaternion.z *= -1;
  94285. this._camera.rotationQuaternion.w *= -1;
  94286. };
  94287. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  94288. return "FreeCameraDeviceOrientationInput";
  94289. };
  94290. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  94291. return "deviceOrientation";
  94292. };
  94293. return FreeCameraDeviceOrientationInput;
  94294. }());
  94295. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  94296. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  94297. })(BABYLON || (BABYLON = {}));
  94298. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  94299. var BABYLON;
  94300. (function (BABYLON) {
  94301. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  94302. function ArcRotateCameraVRDeviceOrientationInput() {
  94303. this.alphaCorrection = 1;
  94304. this.betaCorrection = 1;
  94305. this.gammaCorrection = 1;
  94306. this._alpha = 0;
  94307. this._gamma = 0;
  94308. this._dirty = false;
  94309. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  94310. }
  94311. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94312. this.camera.attachControl(element, noPreventDefault);
  94313. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  94314. };
  94315. /** @hidden */
  94316. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  94317. if (evt.alpha !== null) {
  94318. this._alpha = +evt.alpha | 0;
  94319. }
  94320. if (evt.gamma !== null) {
  94321. this._gamma = +evt.gamma | 0;
  94322. }
  94323. this._dirty = true;
  94324. };
  94325. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  94326. if (this._dirty) {
  94327. this._dirty = false;
  94328. if (this._gamma < 0) {
  94329. this._gamma = 180 + this._gamma;
  94330. }
  94331. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  94332. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  94333. }
  94334. };
  94335. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94336. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94337. };
  94338. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94339. return "ArcRotateCameraVRDeviceOrientationInput";
  94340. };
  94341. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94342. return "VRDeviceOrientation";
  94343. };
  94344. return ArcRotateCameraVRDeviceOrientationInput;
  94345. }());
  94346. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94347. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94348. })(BABYLON || (BABYLON = {}));
  94349. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94350. var BABYLON;
  94351. (function (BABYLON) {
  94352. var VRCameraMetrics = /** @class */ (function () {
  94353. function VRCameraMetrics() {
  94354. this.compensateDistortion = true;
  94355. }
  94356. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94357. get: function () {
  94358. return this.hResolution / (2 * this.vResolution);
  94359. },
  94360. enumerable: true,
  94361. configurable: true
  94362. });
  94363. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94364. get: function () {
  94365. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94366. },
  94367. enumerable: true,
  94368. configurable: true
  94369. });
  94370. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94371. get: function () {
  94372. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94373. var h = (4 * meters) / this.hScreenSize;
  94374. return BABYLON.Matrix.Translation(h, 0, 0);
  94375. },
  94376. enumerable: true,
  94377. configurable: true
  94378. });
  94379. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94380. get: function () {
  94381. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94382. var h = (4 * meters) / this.hScreenSize;
  94383. return BABYLON.Matrix.Translation(-h, 0, 0);
  94384. },
  94385. enumerable: true,
  94386. configurable: true
  94387. });
  94388. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94389. get: function () {
  94390. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94391. },
  94392. enumerable: true,
  94393. configurable: true
  94394. });
  94395. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94396. get: function () {
  94397. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94398. },
  94399. enumerable: true,
  94400. configurable: true
  94401. });
  94402. VRCameraMetrics.GetDefault = function () {
  94403. var result = new VRCameraMetrics();
  94404. result.hResolution = 1280;
  94405. result.vResolution = 800;
  94406. result.hScreenSize = 0.149759993;
  94407. result.vScreenSize = 0.0935999975;
  94408. result.vScreenCenter = 0.0467999987;
  94409. result.eyeToScreenDistance = 0.0410000011;
  94410. result.lensSeparationDistance = 0.0635000020;
  94411. result.interpupillaryDistance = 0.0640000030;
  94412. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  94413. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  94414. result.postProcessScaleFactor = 1.714605507808412;
  94415. result.lensCenterOffset = 0.151976421;
  94416. return result;
  94417. };
  94418. return VRCameraMetrics;
  94419. }());
  94420. BABYLON.VRCameraMetrics = VRCameraMetrics;
  94421. })(BABYLON || (BABYLON = {}));
  94422. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  94423. var BABYLON;
  94424. (function (BABYLON) {
  94425. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  94426. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94427. });
  94428. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  94429. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94430. });
  94431. /**
  94432. * This represents a WebVR camera.
  94433. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  94434. * @example http://doc.babylonjs.com/how_to/webvr_camera
  94435. */
  94436. var WebVRFreeCamera = /** @class */ (function (_super) {
  94437. __extends(WebVRFreeCamera, _super);
  94438. /**
  94439. * Instantiates a WebVRFreeCamera.
  94440. * @param name The name of the WebVRFreeCamera
  94441. * @param position The starting anchor position for the camera
  94442. * @param scene The scene the camera belongs to
  94443. * @param webVROptions a set of customizable options for the webVRCamera
  94444. */
  94445. function WebVRFreeCamera(name, position, scene, webVROptions) {
  94446. if (webVROptions === void 0) { webVROptions = {}; }
  94447. var _this = _super.call(this, name, position, scene) || this;
  94448. _this.webVROptions = webVROptions;
  94449. /**
  94450. * @hidden
  94451. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  94452. */
  94453. _this._vrDevice = null;
  94454. /**
  94455. * The rawPose of the vrDevice.
  94456. */
  94457. _this.rawPose = null;
  94458. _this._specsVersion = "1.1";
  94459. _this._attached = false;
  94460. _this._descendants = [];
  94461. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  94462. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  94463. /** @hidden */
  94464. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  94465. _this._standingMatrix = null;
  94466. /**
  94467. * Represents device position in babylon space.
  94468. */
  94469. _this.devicePosition = BABYLON.Vector3.Zero();
  94470. /**
  94471. * Represents device rotation in babylon space.
  94472. */
  94473. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  94474. /**
  94475. * The scale of the device to be used when translating from device space to babylon space.
  94476. */
  94477. _this.deviceScaleFactor = 1;
  94478. _this._deviceToWorld = BABYLON.Matrix.Identity();
  94479. _this._worldToDevice = BABYLON.Matrix.Identity();
  94480. /**
  94481. * References to the webVR controllers for the vrDevice.
  94482. */
  94483. _this.controllers = [];
  94484. /**
  94485. * Emits an event when a controller is attached.
  94486. */
  94487. _this.onControllersAttachedObservable = new BABYLON.Observable();
  94488. /**
  94489. * Emits an event when a controller's mesh has been loaded;
  94490. */
  94491. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94492. /**
  94493. * Emits an event when the HMD's pose has been updated.
  94494. */
  94495. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  94496. _this._poseSet = false;
  94497. /**
  94498. * If the rig cameras be used as parent instead of this camera.
  94499. */
  94500. _this.rigParenting = true;
  94501. _this._defaultHeight = undefined;
  94502. _this._htmlElementAttached = null;
  94503. _this._detachIfAttached = function () {
  94504. var vrDisplay = _this.getEngine().getVRDevice();
  94505. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  94506. _this.detachControl(_this._htmlElementAttached);
  94507. }
  94508. };
  94509. _this._workingVector = BABYLON.Vector3.Zero();
  94510. _this._oneVector = BABYLON.Vector3.One();
  94511. _this._workingMatrix = BABYLON.Matrix.Identity();
  94512. _this._cache.position = BABYLON.Vector3.Zero();
  94513. if (webVROptions.defaultHeight) {
  94514. _this._defaultHeight = webVROptions.defaultHeight;
  94515. _this.position.y = _this._defaultHeight;
  94516. }
  94517. _this.minZ = 0.1;
  94518. //legacy support - the compensation boolean was removed.
  94519. if (arguments.length === 5) {
  94520. _this.webVROptions = arguments[4];
  94521. }
  94522. // default webVR options
  94523. if (_this.webVROptions.trackPosition == undefined) {
  94524. _this.webVROptions.trackPosition = true;
  94525. }
  94526. if (_this.webVROptions.controllerMeshes == undefined) {
  94527. _this.webVROptions.controllerMeshes = true;
  94528. }
  94529. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  94530. _this.webVROptions.defaultLightingOnControllers = true;
  94531. }
  94532. _this.rotationQuaternion = new BABYLON.Quaternion();
  94533. if (_this.webVROptions && _this.webVROptions.positionScale) {
  94534. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  94535. }
  94536. //enable VR
  94537. var engine = _this.getEngine();
  94538. _this._onVREnabled = function (success) { if (success) {
  94539. _this.initControllers();
  94540. } };
  94541. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  94542. engine.initWebVR().add(function (event) {
  94543. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  94544. return;
  94545. }
  94546. _this._vrDevice = event.vrDisplay;
  94547. //reset the rig parameters.
  94548. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  94549. if (_this._attached) {
  94550. _this.getEngine().enableVR();
  94551. }
  94552. });
  94553. if (typeof (VRFrameData) !== "undefined")
  94554. _this._frameData = new VRFrameData();
  94555. /**
  94556. * The idea behind the following lines:
  94557. * objects that have the camera as parent should actually have the rig cameras as a parent.
  94558. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  94559. * the second will not show it correctly.
  94560. *
  94561. * To solve this - each object that has the camera as parent will be added to a protected array.
  94562. * When the rig camera renders, it will take this array and set all of those to be its children.
  94563. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  94564. * Amazing!
  94565. */
  94566. scene.onBeforeCameraRenderObservable.add(function (camera) {
  94567. if (camera.parent === _this && _this.rigParenting) {
  94568. _this._descendants = _this.getDescendants(true, function (n) {
  94569. // don't take the cameras or the controllers!
  94570. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  94571. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  94572. return !isController && !isRigCamera;
  94573. });
  94574. _this._descendants.forEach(function (node) {
  94575. node.parent = camera;
  94576. });
  94577. }
  94578. });
  94579. scene.onAfterCameraRenderObservable.add(function (camera) {
  94580. if (camera.parent === _this && _this.rigParenting) {
  94581. _this._descendants.forEach(function (node) {
  94582. node.parent = _this;
  94583. });
  94584. }
  94585. });
  94586. return _this;
  94587. }
  94588. /**
  94589. * Gets the device distance from the ground in meters.
  94590. * @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.
  94591. */
  94592. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  94593. if (this._standingMatrix) {
  94594. // Add standing matrix offset to get real offset from ground in room
  94595. this._standingMatrix.getTranslationToRef(this._workingVector);
  94596. return this._deviceRoomPosition.y + this._workingVector.y;
  94597. }
  94598. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  94599. return this._defaultHeight || 0;
  94600. };
  94601. /**
  94602. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94603. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  94604. */
  94605. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  94606. var _this = this;
  94607. if (callback === void 0) { callback = function (bool) { }; }
  94608. // Use standing matrix if available
  94609. this.getEngine().initWebVRAsync().then(function (result) {
  94610. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  94611. callback(false);
  94612. }
  94613. else {
  94614. _this._standingMatrix = new BABYLON.Matrix();
  94615. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  94616. if (!_this.getScene().useRightHandedSystem) {
  94617. [2, 6, 8, 9, 14].forEach(function (num) {
  94618. if (_this._standingMatrix) {
  94619. _this._standingMatrix.m[num] *= -1;
  94620. }
  94621. });
  94622. }
  94623. callback(true);
  94624. }
  94625. });
  94626. };
  94627. /**
  94628. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94629. * @returns A promise with a boolean set to if the standing matrix is supported.
  94630. */
  94631. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  94632. var _this = this;
  94633. return new Promise(function (res, rej) {
  94634. _this.useStandingMatrix(function (supported) {
  94635. res(supported);
  94636. });
  94637. });
  94638. };
  94639. /**
  94640. * Disposes the camera
  94641. */
  94642. WebVRFreeCamera.prototype.dispose = function () {
  94643. this._detachIfAttached();
  94644. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  94645. _super.prototype.dispose.call(this);
  94646. };
  94647. /**
  94648. * Gets a vrController by name.
  94649. * @param name The name of the controller to retreive
  94650. * @returns the controller matching the name specified or null if not found
  94651. */
  94652. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  94653. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  94654. var gp = _a[_i];
  94655. if (gp.hand === name) {
  94656. return gp;
  94657. }
  94658. }
  94659. return null;
  94660. };
  94661. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  94662. /**
  94663. * The controller corrisponding to the users left hand.
  94664. */
  94665. get: function () {
  94666. if (!this._leftController) {
  94667. this._leftController = this.getControllerByName("left");
  94668. }
  94669. return this._leftController;
  94670. },
  94671. enumerable: true,
  94672. configurable: true
  94673. });
  94674. ;
  94675. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  94676. /**
  94677. * The controller corrisponding to the users right hand.
  94678. */
  94679. get: function () {
  94680. if (!this._rightController) {
  94681. this._rightController = this.getControllerByName("right");
  94682. }
  94683. return this._rightController;
  94684. },
  94685. enumerable: true,
  94686. configurable: true
  94687. });
  94688. ;
  94689. /**
  94690. * Casts a ray forward from the vrCamera's gaze.
  94691. * @param length Length of the ray (default: 100)
  94692. * @returns the ray corrisponding to the gaze
  94693. */
  94694. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  94695. if (length === void 0) { length = 100; }
  94696. if (this.leftCamera) {
  94697. // Use left eye to avoid computation to compute center on every call
  94698. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  94699. }
  94700. else {
  94701. return _super.prototype.getForwardRay.call(this, length);
  94702. }
  94703. };
  94704. /**
  94705. * @hidden
  94706. * Updates the camera based on device's frame data
  94707. */
  94708. WebVRFreeCamera.prototype._checkInputs = function () {
  94709. if (this._vrDevice && this._vrDevice.isPresenting) {
  94710. this._vrDevice.getFrameData(this._frameData);
  94711. this.updateFromDevice(this._frameData.pose);
  94712. }
  94713. _super.prototype._checkInputs.call(this);
  94714. };
  94715. /**
  94716. * Updates the poseControlled values based on the input device pose.
  94717. * @param poseData Pose coming from the device
  94718. */
  94719. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  94720. if (poseData && poseData.orientation) {
  94721. this.rawPose = poseData;
  94722. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  94723. if (this.getScene().useRightHandedSystem) {
  94724. this._deviceRoomRotationQuaternion.z *= -1;
  94725. this._deviceRoomRotationQuaternion.w *= -1;
  94726. }
  94727. if (this.webVROptions.trackPosition && this.rawPose.position) {
  94728. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  94729. if (this.getScene().useRightHandedSystem) {
  94730. this._deviceRoomPosition.z *= -1;
  94731. }
  94732. }
  94733. this._poseSet = true;
  94734. }
  94735. };
  94736. /**
  94737. * WebVR's attach control will start broadcasting frames to the device.
  94738. * Note that in certain browsers (chrome for example) this function must be called
  94739. * within a user-interaction callback. Example:
  94740. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  94741. *
  94742. * @param element html element to attach the vrDevice to
  94743. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  94744. */
  94745. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  94746. _super.prototype.attachControl.call(this, element, noPreventDefault);
  94747. this._attached = true;
  94748. this._htmlElementAttached = element;
  94749. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  94750. if (this._vrDevice) {
  94751. this.getEngine().enableVR();
  94752. }
  94753. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  94754. };
  94755. /**
  94756. * Detaches the camera from the html element and disables VR
  94757. *
  94758. * @param element html element to detach from
  94759. */
  94760. WebVRFreeCamera.prototype.detachControl = function (element) {
  94761. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  94762. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  94763. _super.prototype.detachControl.call(this, element);
  94764. this._attached = false;
  94765. this.getEngine().disableVR();
  94766. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  94767. };
  94768. /**
  94769. * @returns the name of this class
  94770. */
  94771. WebVRFreeCamera.prototype.getClassName = function () {
  94772. return "WebVRFreeCamera";
  94773. };
  94774. /**
  94775. * Calls resetPose on the vrDisplay
  94776. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  94777. */
  94778. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  94779. //uses the vrDisplay's "resetPose()".
  94780. //pitch and roll won't be affected.
  94781. this._vrDevice.resetPose();
  94782. };
  94783. /**
  94784. * @hidden
  94785. * Updates the rig cameras (left and right eye)
  94786. */
  94787. WebVRFreeCamera.prototype._updateRigCameras = function () {
  94788. var camLeft = this._rigCameras[0];
  94789. var camRight = this._rigCameras[1];
  94790. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  94791. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  94792. camLeft.position.copyFrom(this._deviceRoomPosition);
  94793. camRight.position.copyFrom(this._deviceRoomPosition);
  94794. };
  94795. /**
  94796. * @hidden
  94797. * Updates the cached values of the camera
  94798. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  94799. */
  94800. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  94801. var _this = this;
  94802. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  94803. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  94804. if (!this.updateCacheCalled) {
  94805. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  94806. this.updateCacheCalled = true;
  94807. this.update();
  94808. }
  94809. // Set working vector to the device position in room space rotated by the new rotation
  94810. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  94811. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  94812. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  94813. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  94814. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  94815. // Add translation from anchor position
  94816. this._deviceToWorld.getTranslationToRef(this._workingVector);
  94817. this._workingVector.addInPlace(this.position);
  94818. this._workingVector.subtractInPlace(this._cache.position);
  94819. this._deviceToWorld.setTranslation(this._workingVector);
  94820. // Set an inverted matrix to be used when updating the camera
  94821. this._deviceToWorld.invertToRef(this._worldToDevice);
  94822. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  94823. this.controllers.forEach(function (controller) {
  94824. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  94825. controller.update();
  94826. });
  94827. }
  94828. if (!ignoreParentClass) {
  94829. _super.prototype._updateCache.call(this);
  94830. }
  94831. this.updateCacheCalled = false;
  94832. };
  94833. /**
  94834. * Updates the current device position and rotation in the babylon world
  94835. */
  94836. WebVRFreeCamera.prototype.update = function () {
  94837. // Get current device position in babylon world
  94838. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  94839. // Get current device rotation in babylon world
  94840. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  94841. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  94842. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  94843. if (this._poseSet) {
  94844. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  94845. }
  94846. _super.prototype.update.call(this);
  94847. };
  94848. /**
  94849. * @hidden
  94850. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  94851. * @returns an identity matrix
  94852. */
  94853. WebVRFreeCamera.prototype._getViewMatrix = function () {
  94854. return BABYLON.Matrix.Identity();
  94855. };
  94856. /**
  94857. * This function is called by the two RIG cameras.
  94858. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  94859. */
  94860. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  94861. var _this = this;
  94862. // Update the parent camera prior to using a child camera to avoid desynchronization
  94863. var parentCamera = this._cameraRigParams["parentCamera"];
  94864. parentCamera._updateCache();
  94865. //WebVR 1.1
  94866. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  94867. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  94868. if (!this.getScene().useRightHandedSystem) {
  94869. [2, 6, 8, 9, 14].forEach(function (num) {
  94870. _this._webvrViewMatrix.m[num] *= -1;
  94871. });
  94872. }
  94873. // update the camera rotation matrix
  94874. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  94875. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  94876. // Computing target and final matrix
  94877. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  94878. // should the view matrix be updated with scale and position offset?
  94879. if (parentCamera.deviceScaleFactor !== 1) {
  94880. this._webvrViewMatrix.invert();
  94881. // scale the position, if set
  94882. if (parentCamera.deviceScaleFactor) {
  94883. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  94884. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  94885. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  94886. }
  94887. this._webvrViewMatrix.invert();
  94888. }
  94889. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  94890. // Compute global position
  94891. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  94892. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  94893. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  94894. this._workingMatrix.getTranslationToRef(this._globalPosition);
  94895. this._markSyncedWithParent();
  94896. return this._webvrViewMatrix;
  94897. };
  94898. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  94899. var _this = this;
  94900. var parentCamera = this.parent;
  94901. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  94902. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  94903. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  94904. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  94905. //babylon compatible matrix
  94906. if (!this.getScene().useRightHandedSystem) {
  94907. [8, 9, 10, 11].forEach(function (num) {
  94908. _this._projectionMatrix.m[num] *= -1;
  94909. });
  94910. }
  94911. return this._projectionMatrix;
  94912. };
  94913. /**
  94914. * Initializes the controllers and their meshes
  94915. */
  94916. WebVRFreeCamera.prototype.initControllers = function () {
  94917. var _this = this;
  94918. this.controllers = [];
  94919. var manager = this.getScene().gamepadManager;
  94920. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  94921. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  94922. var webVrController = gamepad;
  94923. if (webVrController.defaultModel) {
  94924. webVrController.defaultModel.setEnabled(false);
  94925. }
  94926. if (webVrController.hand === "right") {
  94927. _this._rightController = null;
  94928. }
  94929. if (webVrController.hand === "left") {
  94930. _this._leftController = null;
  94931. }
  94932. var controllerIndex = _this.controllers.indexOf(webVrController);
  94933. if (controllerIndex !== -1) {
  94934. _this.controllers.splice(controllerIndex, 1);
  94935. }
  94936. }
  94937. });
  94938. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  94939. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  94940. var webVrController_1 = gamepad;
  94941. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  94942. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  94943. if (_this.webVROptions.controllerMeshes) {
  94944. if (webVrController_1.defaultModel) {
  94945. webVrController_1.defaultModel.setEnabled(true);
  94946. }
  94947. else {
  94948. // Load the meshes
  94949. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  94950. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  94951. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  94952. if (_this.webVROptions.defaultLightingOnControllers) {
  94953. if (!_this._lightOnControllers) {
  94954. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  94955. }
  94956. var activateLightOnSubMeshes_1 = function (mesh, light) {
  94957. var children = mesh.getChildren();
  94958. if (children.length !== 0) {
  94959. children.forEach(function (mesh) {
  94960. light.includedOnlyMeshes.push(mesh);
  94961. activateLightOnSubMeshes_1(mesh, light);
  94962. });
  94963. }
  94964. };
  94965. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  94966. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  94967. }
  94968. });
  94969. }
  94970. }
  94971. webVrController_1.attachToPoseControlledCamera(_this);
  94972. // since this is async - sanity check. Is the controller already stored?
  94973. if (_this.controllers.indexOf(webVrController_1) === -1) {
  94974. //add to the controllers array
  94975. _this.controllers.push(webVrController_1);
  94976. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  94977. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  94978. // So we're overriding setting left & right manually to be sure
  94979. var firstViveWandDetected = false;
  94980. for (var i = 0; i < _this.controllers.length; i++) {
  94981. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94982. if (!firstViveWandDetected) {
  94983. firstViveWandDetected = true;
  94984. _this.controllers[i].hand = "left";
  94985. }
  94986. else {
  94987. _this.controllers[i].hand = "right";
  94988. }
  94989. }
  94990. }
  94991. //did we find enough controllers? Great! let the developer know.
  94992. if (_this.controllers.length >= 2) {
  94993. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  94994. }
  94995. }
  94996. }
  94997. });
  94998. };
  94999. return WebVRFreeCamera;
  95000. }(BABYLON.FreeCamera));
  95001. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  95002. })(BABYLON || (BABYLON = {}));
  95003. //# sourceMappingURL=babylon.webVRCamera.js.map
  95004. var BABYLON;
  95005. (function (BABYLON) {
  95006. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  95007. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  95008. });
  95009. // We're mainly based on the logic defined into the FreeCamera code
  95010. /**
  95011. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  95012. * being tilted forward or back and left or right.
  95013. */
  95014. var DeviceOrientationCamera = /** @class */ (function (_super) {
  95015. __extends(DeviceOrientationCamera, _super);
  95016. /**
  95017. * Creates a new device orientation camera
  95018. * @param name The name of the camera
  95019. * @param position The start position camera
  95020. * @param scene The scene the camera belongs to
  95021. */
  95022. function DeviceOrientationCamera(name, position, scene) {
  95023. var _this = _super.call(this, name, position, scene) || this;
  95024. _this._quaternionCache = new BABYLON.Quaternion();
  95025. _this.inputs.addDeviceOrientation();
  95026. return _this;
  95027. }
  95028. /**
  95029. * Gets the current instance class name ("DeviceOrientationCamera").
  95030. * This helps avoiding instanceof at run time.
  95031. * @returns the class name
  95032. */
  95033. DeviceOrientationCamera.prototype.getClassName = function () {
  95034. return "DeviceOrientationCamera";
  95035. };
  95036. /**
  95037. * @hidden
  95038. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  95039. */
  95040. DeviceOrientationCamera.prototype._checkInputs = function () {
  95041. _super.prototype._checkInputs.call(this);
  95042. this._quaternionCache.copyFrom(this.rotationQuaternion);
  95043. if (this._initialQuaternion) {
  95044. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95045. }
  95046. };
  95047. /**
  95048. * Reset the camera to its default orientation on the specified axis only.
  95049. * @param axis The axis to reset
  95050. */
  95051. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  95052. var _this = this;
  95053. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  95054. //can only work if this camera has a rotation quaternion already.
  95055. if (!this.rotationQuaternion)
  95056. return;
  95057. if (!this._initialQuaternion) {
  95058. this._initialQuaternion = new BABYLON.Quaternion();
  95059. }
  95060. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  95061. ['x', 'y', 'z'].forEach(function (axisName) {
  95062. if (!axis[axisName]) {
  95063. _this._initialQuaternion[axisName] = 0;
  95064. }
  95065. else {
  95066. _this._initialQuaternion[axisName] *= -1;
  95067. }
  95068. });
  95069. this._initialQuaternion.normalize();
  95070. //force rotation update
  95071. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95072. };
  95073. return DeviceOrientationCamera;
  95074. }(BABYLON.FreeCamera));
  95075. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  95076. })(BABYLON || (BABYLON = {}));
  95077. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  95078. var BABYLON;
  95079. (function (BABYLON) {
  95080. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95081. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95082. });
  95083. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  95084. __extends(VRDeviceOrientationFreeCamera, _super);
  95085. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95086. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95087. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95088. var _this = _super.call(this, name, position, scene) || this;
  95089. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95090. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95091. return _this;
  95092. }
  95093. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  95094. return "VRDeviceOrientationFreeCamera";
  95095. };
  95096. return VRDeviceOrientationFreeCamera;
  95097. }(BABYLON.DeviceOrientationCamera));
  95098. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  95099. })(BABYLON || (BABYLON = {}));
  95100. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  95101. var BABYLON;
  95102. (function (BABYLON) {
  95103. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95104. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  95105. });
  95106. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  95107. __extends(VRDeviceOrientationArcRotateCamera, _super);
  95108. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  95109. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95110. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95111. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95112. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95113. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95114. _this.inputs.addVRDeviceOrientation();
  95115. return _this;
  95116. }
  95117. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  95118. return "VRDeviceOrientationArcRotateCamera";
  95119. };
  95120. return VRDeviceOrientationArcRotateCamera;
  95121. }(BABYLON.ArcRotateCamera));
  95122. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  95123. })(BABYLON || (BABYLON = {}));
  95124. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  95125. var BABYLON;
  95126. (function (BABYLON) {
  95127. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  95128. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  95129. });
  95130. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  95131. __extends(VRDeviceOrientationGamepadCamera, _super);
  95132. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95133. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95134. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95135. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  95136. _this.inputs.addGamepad();
  95137. return _this;
  95138. }
  95139. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  95140. return "VRDeviceOrientationGamepadCamera";
  95141. };
  95142. return VRDeviceOrientationGamepadCamera;
  95143. }(BABYLON.VRDeviceOrientationFreeCamera));
  95144. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  95145. })(BABYLON || (BABYLON = {}));
  95146. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  95147. var BABYLON;
  95148. (function (BABYLON) {
  95149. var VRExperienceHelperGazer = /** @class */ (function () {
  95150. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  95151. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  95152. this.scene = scene;
  95153. /** @hidden */
  95154. this._pointerDownOnMeshAsked = false;
  95155. /** @hidden */
  95156. this._isActionableMesh = false;
  95157. /** @hidden */
  95158. this._teleportationRequestInitiated = false;
  95159. /** @hidden */
  95160. this._teleportationBackRequestInitiated = false;
  95161. /** @hidden */
  95162. this._rotationRightAsked = false;
  95163. /** @hidden */
  95164. this._rotationLeftAsked = false;
  95165. /** @hidden */
  95166. this._dpadPressed = true;
  95167. /** @hidden */
  95168. this._activePointer = false;
  95169. this._id = VRExperienceHelperGazer._idCounter++;
  95170. // Gaze tracker
  95171. if (!gazeTrackerToClone) {
  95172. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  95173. this._gazeTracker.bakeCurrentTransformIntoVertices();
  95174. this._gazeTracker.isPickable = false;
  95175. this._gazeTracker.isVisible = false;
  95176. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  95177. targetMat.specularColor = BABYLON.Color3.Black();
  95178. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95179. targetMat.backFaceCulling = false;
  95180. this._gazeTracker.material = targetMat;
  95181. }
  95182. else {
  95183. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  95184. }
  95185. }
  95186. /** @hidden */
  95187. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  95188. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  95189. };
  95190. /** @hidden */
  95191. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  95192. this._pointerDownOnMeshAsked = true;
  95193. if (this._currentHit) {
  95194. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  95195. }
  95196. };
  95197. /** @hidden */
  95198. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  95199. if (this._currentHit) {
  95200. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  95201. }
  95202. this._pointerDownOnMeshAsked = false;
  95203. };
  95204. /** @hidden */
  95205. VRExperienceHelperGazer.prototype._activatePointer = function () {
  95206. this._activePointer = true;
  95207. };
  95208. /** @hidden */
  95209. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  95210. this._activePointer = false;
  95211. };
  95212. /** @hidden */
  95213. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  95214. if (distance === void 0) { distance = 100; }
  95215. };
  95216. VRExperienceHelperGazer.prototype.dispose = function () {
  95217. this._interactionsEnabled = false;
  95218. this._teleportationEnabled = false;
  95219. if (this._gazeTracker) {
  95220. this._gazeTracker.dispose();
  95221. }
  95222. };
  95223. VRExperienceHelperGazer._idCounter = 0;
  95224. return VRExperienceHelperGazer;
  95225. }());
  95226. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  95227. __extends(VRExperienceHelperControllerGazer, _super);
  95228. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  95229. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  95230. _this.webVRController = webVRController;
  95231. // Laser pointer
  95232. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  95233. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  95234. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95235. laserPointerMaterial.alpha = 0.6;
  95236. _this._laserPointer.material = laserPointerMaterial;
  95237. _this._laserPointer.rotation.x = Math.PI / 2;
  95238. _this._laserPointer.position.z = -0.5;
  95239. _this._laserPointer.isVisible = false;
  95240. _this._laserPointer.isPickable = false;
  95241. if (!webVRController.mesh) {
  95242. // Create an empty mesh that is used prior to loading the high quality model
  95243. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  95244. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  95245. preloadPointerPose.rotation.x = -0.7;
  95246. preloadMesh.addChild(preloadPointerPose);
  95247. webVRController.attachToMesh(preloadMesh);
  95248. }
  95249. _this._setLaserPointerParent(webVRController.mesh);
  95250. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  95251. _this._setLaserPointerParent(mesh);
  95252. });
  95253. return _this;
  95254. }
  95255. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  95256. return this.webVRController.getForwardRay(length);
  95257. };
  95258. /** @hidden */
  95259. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  95260. _super.prototype._activatePointer.call(this);
  95261. this._laserPointer.isVisible = true;
  95262. };
  95263. /** @hidden */
  95264. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  95265. _super.prototype._deactivatePointer.call(this);
  95266. this._laserPointer.isVisible = false;
  95267. };
  95268. /** @hidden */
  95269. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  95270. this._laserPointer.material.emissiveColor = color;
  95271. };
  95272. /** @hidden */
  95273. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  95274. var makeNotPick = function (root) {
  95275. root.isPickable = false;
  95276. root.getChildMeshes().forEach(function (c) {
  95277. makeNotPick(c);
  95278. });
  95279. };
  95280. makeNotPick(mesh);
  95281. var childMeshes = mesh.getChildMeshes();
  95282. this.webVRController._pointingPoseNode = null;
  95283. for (var i = 0; i < childMeshes.length; i++) {
  95284. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  95285. mesh = childMeshes[i];
  95286. this.webVRController._pointingPoseNode = mesh;
  95287. break;
  95288. }
  95289. }
  95290. this._laserPointer.parent = mesh;
  95291. };
  95292. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  95293. if (distance === void 0) { distance = 100; }
  95294. this._laserPointer.scaling.y = distance;
  95295. this._laserPointer.position.z = -distance / 2;
  95296. };
  95297. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  95298. _super.prototype.dispose.call(this);
  95299. this._laserPointer.dispose();
  95300. if (this._meshAttachedObserver) {
  95301. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  95302. }
  95303. };
  95304. return VRExperienceHelperControllerGazer;
  95305. }(VRExperienceHelperGazer));
  95306. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  95307. __extends(VRExperienceHelperCameraGazer, _super);
  95308. function VRExperienceHelperCameraGazer(getCamera, scene) {
  95309. var _this = _super.call(this, scene) || this;
  95310. _this.getCamera = getCamera;
  95311. return _this;
  95312. }
  95313. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  95314. var camera = this.getCamera();
  95315. if (camera) {
  95316. return camera.getForwardRay(length);
  95317. }
  95318. else {
  95319. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  95320. }
  95321. };
  95322. return VRExperienceHelperCameraGazer;
  95323. }(VRExperienceHelperGazer));
  95324. /**
  95325. * Helps to quickly add VR support to an existing scene.
  95326. * See http://doc.babylonjs.com/how_to/webvr_helper
  95327. */
  95328. var VRExperienceHelper = /** @class */ (function () {
  95329. /**
  95330. * Instantiates a VRExperienceHelper.
  95331. * Helps to quickly add VR support to an existing scene.
  95332. * @param scene The scene the VRExperienceHelper belongs to.
  95333. * @param webVROptions Options to modify the vr experience helper's behavior.
  95334. */
  95335. function VRExperienceHelper(scene,
  95336. /** Options to modify the vr experience helper's behavior. */
  95337. webVROptions) {
  95338. if (webVROptions === void 0) { webVROptions = {}; }
  95339. var _this = this;
  95340. this.webVROptions = webVROptions;
  95341. // Can the system support WebVR, even if a headset isn't plugged in?
  95342. this._webVRsupported = false;
  95343. // If WebVR is supported, is a headset plugged in and are we ready to present?
  95344. this._webVRready = false;
  95345. // Are we waiting for the requestPresent callback to complete?
  95346. this._webVRrequesting = false;
  95347. // Are we presenting to the headset right now? (this is the vrDevice state)
  95348. this._webVRpresenting = false;
  95349. // Are we presenting in the fullscreen fallback?
  95350. this._fullscreenVRpresenting = false;
  95351. /**
  95352. * Observable raised when entering VR.
  95353. */
  95354. this.onEnteringVRObservable = new BABYLON.Observable();
  95355. /**
  95356. * Observable raised when exiting VR.
  95357. */
  95358. this.onExitingVRObservable = new BABYLON.Observable();
  95359. /**
  95360. * Observable raised when controller mesh is loaded.
  95361. */
  95362. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95363. this._useCustomVRButton = false;
  95364. this._teleportationRequested = false;
  95365. this._teleportActive = false;
  95366. this._floorMeshesCollection = [];
  95367. this._rotationAllowed = true;
  95368. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95369. this._isDefaultTeleportationTarget = true;
  95370. this._teleportationFillColor = "#444444";
  95371. this._teleportationBorderColor = "#FFFFFF";
  95372. this._rotationAngle = 0;
  95373. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95374. this._padSensibilityUp = 0.65;
  95375. this._padSensibilityDown = 0.35;
  95376. this._leftController = null;
  95377. this._rightController = null;
  95378. /**
  95379. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95380. */
  95381. this.onNewMeshSelected = new BABYLON.Observable();
  95382. /**
  95383. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95384. */
  95385. this.onNewMeshPicked = new BABYLON.Observable();
  95386. /**
  95387. * Observable raised before camera teleportation
  95388. */
  95389. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95390. /**
  95391. * Observable raised after camera teleportation
  95392. */
  95393. this.onAfterCameraTeleport = new BABYLON.Observable();
  95394. /**
  95395. * Observable raised when current selected mesh gets unselected
  95396. */
  95397. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95398. /**
  95399. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95400. */
  95401. this.teleportationEnabled = true;
  95402. this._teleportationInitialized = false;
  95403. this._interactionsEnabled = false;
  95404. this._interactionsRequested = false;
  95405. this._displayGaze = true;
  95406. this._displayLaserPointer = true;
  95407. this._onResize = function () {
  95408. _this.moveButtonToBottomRight();
  95409. if (_this._fullscreenVRpresenting && _this._webVRready) {
  95410. _this.exitVR();
  95411. }
  95412. };
  95413. this._onFullscreenChange = function () {
  95414. if (document.fullscreen !== undefined) {
  95415. _this._fullscreenVRpresenting = document.fullscreen;
  95416. }
  95417. else if (document.mozFullScreen !== undefined) {
  95418. _this._fullscreenVRpresenting = document.mozFullScreen;
  95419. }
  95420. else if (document.webkitIsFullScreen !== undefined) {
  95421. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  95422. }
  95423. else if (document.msIsFullScreen !== undefined) {
  95424. _this._fullscreenVRpresenting = document.msIsFullScreen;
  95425. }
  95426. else if (document.msFullscreenElement !== undefined) {
  95427. _this._fullscreenVRpresenting = document.msFullscreenElement;
  95428. }
  95429. if (!_this._fullscreenVRpresenting && _this._canvas) {
  95430. _this.exitVR();
  95431. if (!_this._useCustomVRButton) {
  95432. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  95433. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  95434. }
  95435. }
  95436. };
  95437. this.beforeRender = function () {
  95438. if (_this._leftController && _this._leftController._activePointer) {
  95439. _this._castRayAndSelectObject(_this._leftController);
  95440. }
  95441. if (_this._rightController && _this._rightController._activePointer) {
  95442. _this._castRayAndSelectObject(_this._rightController);
  95443. }
  95444. if (_this._noControllerIsActive) {
  95445. _this._castRayAndSelectObject(_this._cameraGazer);
  95446. }
  95447. else {
  95448. _this._cameraGazer._gazeTracker.isVisible = false;
  95449. }
  95450. };
  95451. this._onNewGamepadConnected = function (gamepad) {
  95452. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  95453. if (gamepad.leftStick) {
  95454. gamepad.onleftstickchanged(function (stickValues) {
  95455. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  95456. // Listening to classic/xbox gamepad only if no VR controller is active
  95457. if ((!_this._leftController && !_this._rightController) ||
  95458. ((_this._leftController && !_this._leftController._activePointer) &&
  95459. (_this._rightController && !_this._rightController._activePointer))) {
  95460. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  95461. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  95462. }
  95463. }
  95464. });
  95465. }
  95466. if (gamepad.rightStick) {
  95467. gamepad.onrightstickchanged(function (stickValues) {
  95468. if (_this._teleportationInitialized) {
  95469. _this._checkRotate(stickValues, _this._cameraGazer);
  95470. }
  95471. });
  95472. }
  95473. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  95474. gamepad.onbuttondown(function (buttonPressed) {
  95475. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95476. _this._cameraGazer._selectionPointerDown();
  95477. }
  95478. });
  95479. gamepad.onbuttonup(function (buttonPressed) {
  95480. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95481. _this._cameraGazer._selectionPointerUp();
  95482. }
  95483. });
  95484. }
  95485. }
  95486. else {
  95487. var webVRController = gamepad;
  95488. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  95489. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  95490. _this._rightController = controller;
  95491. }
  95492. else {
  95493. _this._leftController = controller;
  95494. }
  95495. _this._tryEnableInteractionOnController(controller);
  95496. }
  95497. };
  95498. // 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
  95499. this._tryEnableInteractionOnController = function (controller) {
  95500. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  95501. _this._enableInteractionOnController(controller);
  95502. }
  95503. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  95504. _this._enableTeleportationOnController(controller);
  95505. }
  95506. };
  95507. this._onNewGamepadDisconnected = function (gamepad) {
  95508. if (gamepad instanceof BABYLON.WebVRController) {
  95509. if (gamepad.hand === "left" && _this._leftController != null) {
  95510. _this._leftController.dispose();
  95511. _this._leftController = null;
  95512. }
  95513. if (gamepad.hand === "right" && _this._rightController != null) {
  95514. _this._rightController.dispose();
  95515. _this._rightController = null;
  95516. }
  95517. }
  95518. };
  95519. this._workingVector = BABYLON.Vector3.Zero();
  95520. this._workingQuaternion = BABYLON.Quaternion.Identity();
  95521. this._workingMatrix = BABYLON.Matrix.Identity();
  95522. this._scene = scene;
  95523. this._canvas = scene.getEngine().getRenderingCanvas();
  95524. // Parse options
  95525. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  95526. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  95527. }
  95528. if (webVROptions.createDeviceOrientationCamera === undefined) {
  95529. webVROptions.createDeviceOrientationCamera = true;
  95530. }
  95531. if (webVROptions.laserToggle === undefined) {
  95532. webVROptions.laserToggle = true;
  95533. }
  95534. if (webVROptions.defaultHeight === undefined) {
  95535. webVROptions.defaultHeight = 1.7;
  95536. }
  95537. if (webVROptions.useCustomVRButton) {
  95538. this._useCustomVRButton = true;
  95539. if (webVROptions.customVRButton) {
  95540. this._btnVR = webVROptions.customVRButton;
  95541. }
  95542. }
  95543. if (webVROptions.rayLength) {
  95544. this._rayLength = webVROptions.rayLength;
  95545. }
  95546. this._defaultHeight = webVROptions.defaultHeight;
  95547. if (webVROptions.positionScale) {
  95548. this._rayLength *= webVROptions.positionScale;
  95549. this._defaultHeight *= webVROptions.positionScale;
  95550. }
  95551. this._hasEnteredVR = false;
  95552. // Set position
  95553. if (this._scene.activeCamera) {
  95554. this._position = this._scene.activeCamera.position.clone();
  95555. }
  95556. else {
  95557. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  95558. }
  95559. // Set non-vr camera
  95560. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  95561. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  95562. // Copy data from existing camera
  95563. if (this._scene.activeCamera) {
  95564. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95565. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  95566. // Set rotation from previous camera
  95567. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  95568. var targetCamera = this._scene.activeCamera;
  95569. if (targetCamera.rotationQuaternion) {
  95570. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  95571. }
  95572. else {
  95573. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  95574. }
  95575. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  95576. }
  95577. }
  95578. this._scene.activeCamera = this._deviceOrientationCamera;
  95579. if (this._canvas) {
  95580. this._scene.activeCamera.attachControl(this._canvas);
  95581. }
  95582. }
  95583. else {
  95584. this._existingCamera = this._scene.activeCamera;
  95585. }
  95586. // Create VR cameras
  95587. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95588. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  95589. }
  95590. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  95591. this._webVRCamera.useStandingMatrix();
  95592. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  95593. // Create default button
  95594. if (!this._useCustomVRButton) {
  95595. this._btnVR = document.createElement("BUTTON");
  95596. this._btnVR.className = "babylonVRicon";
  95597. this._btnVR.id = "babylonVRiconbtn";
  95598. this._btnVR.title = "Click to switch to VR";
  95599. 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) }";
  95600. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  95601. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  95602. // css += ".babylonVRicon.vrdisplaysupported { }";
  95603. // css += ".babylonVRicon.vrdisplayready { }";
  95604. // css += ".babylonVRicon.vrdisplayrequesting { }";
  95605. var style = document.createElement('style');
  95606. style.appendChild(document.createTextNode(css));
  95607. document.getElementsByTagName('head')[0].appendChild(style);
  95608. this.moveButtonToBottomRight();
  95609. }
  95610. // VR button click event
  95611. if (this._btnVR) {
  95612. this._btnVR.addEventListener("click", function () {
  95613. if (!_this.isInVRMode) {
  95614. _this.enterVR();
  95615. }
  95616. else {
  95617. _this.exitVR();
  95618. }
  95619. });
  95620. }
  95621. // Window events
  95622. window.addEventListener("resize", this._onResize);
  95623. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  95624. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  95625. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  95626. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  95627. document.onmsfullscreenchange = this._onFullscreenChange;
  95628. // Display vr button when headset is connected
  95629. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95630. this.displayVRButton();
  95631. }
  95632. else {
  95633. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  95634. if (e.vrDisplay) {
  95635. _this.displayVRButton();
  95636. }
  95637. });
  95638. }
  95639. // Exiting VR mode using 'ESC' key on desktop
  95640. this._onKeyDown = function (event) {
  95641. if (event.keyCode === 27 && _this.isInVRMode) {
  95642. _this.exitVR();
  95643. }
  95644. };
  95645. document.addEventListener("keydown", this._onKeyDown);
  95646. // Exiting VR mode double tapping the touch screen
  95647. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  95648. if (_this.isInVRMode) {
  95649. _this.exitVR();
  95650. if (_this._fullscreenVRpresenting) {
  95651. _this._scene.getEngine().switchFullscreen(true);
  95652. }
  95653. }
  95654. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  95655. // Listen for WebVR display changes
  95656. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  95657. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  95658. this._onVRRequestPresentStart = function () {
  95659. _this._webVRrequesting = true;
  95660. _this.updateButtonVisibility();
  95661. };
  95662. this._onVRRequestPresentComplete = function (success) {
  95663. _this._webVRrequesting = false;
  95664. _this.updateButtonVisibility();
  95665. };
  95666. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  95667. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  95668. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  95669. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95670. scene.onDisposeObservable.add(function () {
  95671. _this.dispose();
  95672. });
  95673. // Gamepad connection events
  95674. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  95675. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  95676. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  95677. this.updateButtonVisibility();
  95678. //create easing functions
  95679. this._circleEase = new BABYLON.CircleEase();
  95680. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  95681. if (this.webVROptions.floorMeshes) {
  95682. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  95683. }
  95684. }
  95685. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  95686. /** Return this.onEnteringVRObservable
  95687. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  95688. */
  95689. get: function () {
  95690. return this.onEnteringVRObservable;
  95691. },
  95692. enumerable: true,
  95693. configurable: true
  95694. });
  95695. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  95696. /** Return this.onExitingVRObservable
  95697. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  95698. */
  95699. get: function () {
  95700. return this.onExitingVRObservable;
  95701. },
  95702. enumerable: true,
  95703. configurable: true
  95704. });
  95705. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  95706. /** Return this.onControllerMeshLoadedObservable
  95707. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  95708. */
  95709. get: function () {
  95710. return this.onControllerMeshLoadedObservable;
  95711. },
  95712. enumerable: true,
  95713. configurable: true
  95714. });
  95715. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  95716. /**
  95717. * The mesh used to display where the user is going to teleport.
  95718. */
  95719. get: function () {
  95720. return this._teleportationTarget;
  95721. },
  95722. /**
  95723. * Sets the mesh to be used to display where the user is going to teleport.
  95724. */
  95725. set: function (value) {
  95726. if (value) {
  95727. value.name = "teleportationTarget";
  95728. this._isDefaultTeleportationTarget = false;
  95729. this._teleportationTarget = value;
  95730. }
  95731. },
  95732. enumerable: true,
  95733. configurable: true
  95734. });
  95735. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  95736. /**
  95737. * The mesh used to display where the user is selecting,
  95738. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  95739. * See http://doc.babylonjs.com/resources/baking_transformations
  95740. */
  95741. get: function () {
  95742. return this._cameraGazer._gazeTracker;
  95743. },
  95744. set: function (value) {
  95745. if (value) {
  95746. this._cameraGazer._gazeTracker = value;
  95747. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  95748. this._cameraGazer._gazeTracker.isPickable = false;
  95749. this._cameraGazer._gazeTracker.isVisible = false;
  95750. this._cameraGazer._gazeTracker.name = "gazeTracker";
  95751. if (this._leftController) {
  95752. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  95753. }
  95754. if (this._rightController) {
  95755. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  95756. }
  95757. }
  95758. },
  95759. enumerable: true,
  95760. configurable: true
  95761. });
  95762. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  95763. /**
  95764. * If the ray of the gaze should be displayed.
  95765. */
  95766. get: function () {
  95767. return this._displayGaze;
  95768. },
  95769. /**
  95770. * Sets if the ray of the gaze should be displayed.
  95771. */
  95772. set: function (value) {
  95773. this._displayGaze = value;
  95774. if (!value) {
  95775. this._cameraGazer._gazeTracker.isVisible = false;
  95776. if (this._leftController) {
  95777. this._leftController._gazeTracker.isVisible = false;
  95778. }
  95779. if (this._rightController) {
  95780. this._rightController._gazeTracker.isVisible = false;
  95781. }
  95782. }
  95783. },
  95784. enumerable: true,
  95785. configurable: true
  95786. });
  95787. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  95788. /**
  95789. * If the ray of the LaserPointer should be displayed.
  95790. */
  95791. get: function () {
  95792. return this._displayLaserPointer;
  95793. },
  95794. /**
  95795. * Sets if the ray of the LaserPointer should be displayed.
  95796. */
  95797. set: function (value) {
  95798. this._displayLaserPointer = value;
  95799. if (!value) {
  95800. if (this._rightController) {
  95801. this._rightController._deactivatePointer();
  95802. this._rightController._gazeTracker.isVisible = false;
  95803. }
  95804. if (this._leftController) {
  95805. this._leftController._deactivatePointer();
  95806. this._leftController._gazeTracker.isVisible = false;
  95807. }
  95808. }
  95809. else {
  95810. if (this._rightController) {
  95811. this._rightController._activatePointer();
  95812. }
  95813. if (this._leftController) {
  95814. this._leftController._activatePointer();
  95815. }
  95816. }
  95817. },
  95818. enumerable: true,
  95819. configurable: true
  95820. });
  95821. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  95822. /**
  95823. * The deviceOrientationCamera used as the camera when not in VR.
  95824. */
  95825. get: function () {
  95826. return this._deviceOrientationCamera;
  95827. },
  95828. enumerable: true,
  95829. configurable: true
  95830. });
  95831. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  95832. /**
  95833. * Based on the current WebVR support, returns the current VR camera used.
  95834. */
  95835. get: function () {
  95836. if (this._webVRready) {
  95837. return this._webVRCamera;
  95838. }
  95839. else {
  95840. return this._scene.activeCamera;
  95841. }
  95842. },
  95843. enumerable: true,
  95844. configurable: true
  95845. });
  95846. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  95847. /**
  95848. * The webVRCamera which is used when in VR.
  95849. */
  95850. get: function () {
  95851. return this._webVRCamera;
  95852. },
  95853. enumerable: true,
  95854. configurable: true
  95855. });
  95856. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  95857. /**
  95858. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  95859. */
  95860. get: function () {
  95861. return this._vrDeviceOrientationCamera;
  95862. },
  95863. enumerable: true,
  95864. configurable: true
  95865. });
  95866. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  95867. get: function () {
  95868. var result = this._cameraGazer._teleportationRequestInitiated
  95869. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  95870. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  95871. return result;
  95872. },
  95873. enumerable: true,
  95874. configurable: true
  95875. });
  95876. // Raised when one of the controller has loaded successfully its associated default mesh
  95877. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  95878. if (this._leftController && this._leftController.webVRController == webVRController) {
  95879. if (webVRController.mesh) {
  95880. this._leftController._setLaserPointerParent(webVRController.mesh);
  95881. }
  95882. }
  95883. if (this._rightController && this._rightController.webVRController == webVRController) {
  95884. if (webVRController.mesh) {
  95885. this._rightController._setLaserPointerParent(webVRController.mesh);
  95886. }
  95887. }
  95888. try {
  95889. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  95890. }
  95891. catch (err) {
  95892. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  95893. }
  95894. };
  95895. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  95896. /**
  95897. * Gets a value indicating if we are currently in VR mode.
  95898. */
  95899. get: function () {
  95900. return this._webVRpresenting || this._fullscreenVRpresenting;
  95901. },
  95902. enumerable: true,
  95903. configurable: true
  95904. });
  95905. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  95906. var vrDisplay = this._scene.getEngine().getVRDevice();
  95907. if (vrDisplay) {
  95908. var wasPresenting = this._webVRpresenting;
  95909. this._webVRpresenting = vrDisplay.isPresenting;
  95910. if (wasPresenting && !this._webVRpresenting)
  95911. this.exitVR();
  95912. }
  95913. else {
  95914. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  95915. }
  95916. this.updateButtonVisibility();
  95917. };
  95918. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  95919. this._webVRsupported = eventArgs.vrSupported;
  95920. this._webVRready = !!eventArgs.vrDisplay;
  95921. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  95922. this.updateButtonVisibility();
  95923. };
  95924. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  95925. if (this._canvas && !this._useCustomVRButton) {
  95926. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  95927. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  95928. }
  95929. };
  95930. VRExperienceHelper.prototype.displayVRButton = function () {
  95931. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  95932. document.body.appendChild(this._btnVR);
  95933. this._btnVRDisplayed = true;
  95934. }
  95935. };
  95936. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  95937. if (!this._btnVR || this._useCustomVRButton) {
  95938. return;
  95939. }
  95940. this._btnVR.className = "babylonVRicon";
  95941. if (this.isInVRMode) {
  95942. this._btnVR.className += " vrdisplaypresenting";
  95943. }
  95944. else {
  95945. if (this._webVRready)
  95946. this._btnVR.className += " vrdisplayready";
  95947. if (this._webVRsupported)
  95948. this._btnVR.className += " vrdisplaysupported";
  95949. if (this._webVRrequesting)
  95950. this._btnVR.className += " vrdisplayrequesting";
  95951. }
  95952. };
  95953. /**
  95954. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  95955. * Otherwise, will use the fullscreen API.
  95956. */
  95957. VRExperienceHelper.prototype.enterVR = function () {
  95958. if (this.onEnteringVRObservable) {
  95959. try {
  95960. this.onEnteringVRObservable.notifyObservers(this);
  95961. }
  95962. catch (err) {
  95963. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  95964. }
  95965. }
  95966. if (this._scene.activeCamera) {
  95967. this._position = this._scene.activeCamera.position.clone();
  95968. // make sure that we return to the last active camera
  95969. this._existingCamera = this._scene.activeCamera;
  95970. }
  95971. if (this._webVRrequesting)
  95972. return;
  95973. // If WebVR is supported and a headset is connected
  95974. if (this._webVRready) {
  95975. if (!this._webVRpresenting) {
  95976. this._webVRCamera.position = this._position;
  95977. this._scene.activeCamera = this._webVRCamera;
  95978. }
  95979. }
  95980. else if (this._vrDeviceOrientationCamera) {
  95981. this._vrDeviceOrientationCamera.position = this._position;
  95982. if (this._scene.activeCamera) {
  95983. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95984. }
  95985. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  95986. this._scene.getEngine().switchFullscreen(true);
  95987. this.updateButtonVisibility();
  95988. }
  95989. if (this._scene.activeCamera && this._canvas) {
  95990. this._scene.activeCamera.attachControl(this._canvas);
  95991. }
  95992. if (this._interactionsEnabled) {
  95993. this._scene.registerBeforeRender(this.beforeRender);
  95994. }
  95995. this._hasEnteredVR = true;
  95996. };
  95997. /**
  95998. * Attempt to exit VR, or fullscreen.
  95999. */
  96000. VRExperienceHelper.prototype.exitVR = function () {
  96001. if (this._hasEnteredVR) {
  96002. if (this.onExitingVRObservable) {
  96003. try {
  96004. this.onExitingVRObservable.notifyObservers(this);
  96005. }
  96006. catch (err) {
  96007. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  96008. }
  96009. }
  96010. if (this._webVRpresenting) {
  96011. this._scene.getEngine().disableVR();
  96012. }
  96013. if (this._scene.activeCamera) {
  96014. this._position = this._scene.activeCamera.position.clone();
  96015. }
  96016. if (this._deviceOrientationCamera) {
  96017. this._deviceOrientationCamera.position = this._position;
  96018. this._scene.activeCamera = this._deviceOrientationCamera;
  96019. if (this._canvas) {
  96020. this._scene.activeCamera.attachControl(this._canvas);
  96021. }
  96022. }
  96023. else if (this._existingCamera) {
  96024. this._existingCamera.position = this._position;
  96025. this._scene.activeCamera = this._existingCamera;
  96026. }
  96027. this.updateButtonVisibility();
  96028. if (this._interactionsEnabled) {
  96029. this._scene.unregisterBeforeRender(this.beforeRender);
  96030. this._cameraGazer._gazeTracker.isVisible = false;
  96031. if (this._leftController) {
  96032. this._leftController._gazeTracker.isVisible = false;
  96033. }
  96034. if (this._rightController) {
  96035. this._rightController._gazeTracker.isVisible = false;
  96036. }
  96037. }
  96038. // resize to update width and height when exiting vr exits fullscreen
  96039. this._scene.getEngine().resize();
  96040. this._hasEnteredVR = false;
  96041. }
  96042. };
  96043. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  96044. /**
  96045. * The position of the vr experience helper.
  96046. */
  96047. get: function () {
  96048. return this._position;
  96049. },
  96050. /**
  96051. * Sets the position of the vr experience helper.
  96052. */
  96053. set: function (value) {
  96054. this._position = value;
  96055. if (this._scene.activeCamera) {
  96056. this._scene.activeCamera.position = value;
  96057. }
  96058. },
  96059. enumerable: true,
  96060. configurable: true
  96061. });
  96062. /**
  96063. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  96064. */
  96065. VRExperienceHelper.prototype.enableInteractions = function () {
  96066. var _this = this;
  96067. if (!this._interactionsEnabled) {
  96068. this._interactionsRequested = true;
  96069. if (this._leftController) {
  96070. this._enableInteractionOnController(this._leftController);
  96071. }
  96072. if (this._rightController) {
  96073. this._enableInteractionOnController(this._rightController);
  96074. }
  96075. this.raySelectionPredicate = function (mesh) {
  96076. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  96077. };
  96078. this.meshSelectionPredicate = function (mesh) {
  96079. return true;
  96080. };
  96081. this._raySelectionPredicate = function (mesh) {
  96082. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  96083. && mesh.name.indexOf("teleportationTarget") === -1
  96084. && mesh.name.indexOf("torusTeleportation") === -1)) {
  96085. return _this.raySelectionPredicate(mesh);
  96086. }
  96087. return false;
  96088. };
  96089. this._interactionsEnabled = true;
  96090. }
  96091. };
  96092. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  96093. get: function () {
  96094. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  96095. },
  96096. enumerable: true,
  96097. configurable: true
  96098. });
  96099. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  96100. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  96101. if (this._floorMeshesCollection[i].id === mesh.id) {
  96102. return true;
  96103. }
  96104. }
  96105. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  96106. return true;
  96107. }
  96108. return false;
  96109. };
  96110. /**
  96111. * Adds a floor mesh to be used for teleportation.
  96112. * @param floorMesh the mesh to be used for teleportation.
  96113. */
  96114. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  96115. if (!this._floorMeshesCollection) {
  96116. return;
  96117. }
  96118. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  96119. return;
  96120. }
  96121. this._floorMeshesCollection.push(floorMesh);
  96122. };
  96123. /**
  96124. * Removes a floor mesh from being used for teleportation.
  96125. * @param floorMesh the mesh to be removed.
  96126. */
  96127. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  96128. if (!this._floorMeshesCollection) {
  96129. return;
  96130. }
  96131. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  96132. if (meshIndex !== -1) {
  96133. this._floorMeshesCollection.splice(meshIndex, 1);
  96134. }
  96135. };
  96136. /**
  96137. * Enables interactions and teleportation using the VR controllers and gaze.
  96138. * @param vrTeleportationOptions options to modify teleportation behavior.
  96139. */
  96140. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  96141. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  96142. if (!this._teleportationInitialized) {
  96143. this._teleportationRequested = true;
  96144. this.enableInteractions();
  96145. if (vrTeleportationOptions.floorMeshName) {
  96146. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  96147. }
  96148. if (vrTeleportationOptions.floorMeshes) {
  96149. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  96150. }
  96151. if (this._leftController != null) {
  96152. this._enableTeleportationOnController(this._leftController);
  96153. }
  96154. if (this._rightController != null) {
  96155. this._enableTeleportationOnController(this._rightController);
  96156. }
  96157. // Creates an image processing post process for the vignette not relying
  96158. // on the main scene configuration for image processing to reduce setup and spaces
  96159. // (gamma/linear) conflicts.
  96160. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  96161. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  96162. imageProcessingConfiguration.vignetteEnabled = true;
  96163. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  96164. this._webVRCamera.detachPostProcess(this._postProcessMove);
  96165. this._teleportationInitialized = true;
  96166. if (this._isDefaultTeleportationTarget) {
  96167. this._createTeleportationCircles();
  96168. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  96169. }
  96170. }
  96171. };
  96172. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  96173. var _this = this;
  96174. var controllerMesh = controller.webVRController.mesh;
  96175. if (controllerMesh) {
  96176. controller._interactionsEnabled = true;
  96177. controller._activatePointer();
  96178. if (this.webVROptions.laserToggle) {
  96179. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  96180. // Enabling / disabling laserPointer
  96181. if (_this._displayLaserPointer && stateObject.value === 1) {
  96182. if (controller._activePointer) {
  96183. controller._deactivatePointer();
  96184. }
  96185. else {
  96186. controller._activatePointer();
  96187. }
  96188. if (_this.displayGaze) {
  96189. controller._gazeTracker.isVisible = controller._activePointer;
  96190. }
  96191. }
  96192. });
  96193. }
  96194. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  96195. var gazer = controller;
  96196. if (_this._noControllerIsActive) {
  96197. gazer = _this._cameraGazer;
  96198. }
  96199. if (!gazer._pointerDownOnMeshAsked) {
  96200. if (stateObject.value > _this._padSensibilityUp) {
  96201. gazer._selectionPointerDown();
  96202. }
  96203. }
  96204. else if (stateObject.value < _this._padSensibilityDown) {
  96205. gazer._selectionPointerUp();
  96206. }
  96207. });
  96208. }
  96209. };
  96210. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  96211. // Dont teleport if another gaze already requested teleportation
  96212. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  96213. return;
  96214. }
  96215. if (!gazer._teleportationRequestInitiated) {
  96216. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  96217. gazer._activatePointer();
  96218. gazer._teleportationRequestInitiated = true;
  96219. }
  96220. }
  96221. else {
  96222. // Listening to the proper controller values changes to confirm teleportation
  96223. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  96224. if (this._teleportActive) {
  96225. this._teleportCamera(this._haloCenter);
  96226. }
  96227. gazer._teleportationRequestInitiated = false;
  96228. }
  96229. }
  96230. };
  96231. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  96232. // Only rotate when user is not currently selecting a teleportation location
  96233. if (gazer._teleportationRequestInitiated) {
  96234. return;
  96235. }
  96236. if (!gazer._rotationLeftAsked) {
  96237. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  96238. gazer._rotationLeftAsked = true;
  96239. if (this._rotationAllowed) {
  96240. this._rotateCamera(false);
  96241. }
  96242. }
  96243. }
  96244. else {
  96245. if (stateObject.x > -this._padSensibilityDown) {
  96246. gazer._rotationLeftAsked = false;
  96247. }
  96248. }
  96249. if (!gazer._rotationRightAsked) {
  96250. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  96251. gazer._rotationRightAsked = true;
  96252. if (this._rotationAllowed) {
  96253. this._rotateCamera(true);
  96254. }
  96255. }
  96256. }
  96257. else {
  96258. if (stateObject.x < this._padSensibilityDown) {
  96259. gazer._rotationRightAsked = false;
  96260. }
  96261. }
  96262. };
  96263. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  96264. // Only teleport backwards when user is not currently selecting a teleportation location
  96265. if (gazer._teleportationRequestInitiated) {
  96266. return;
  96267. }
  96268. // Teleport backwards
  96269. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  96270. if (!gazer._teleportationBackRequestInitiated) {
  96271. if (!this.currentVRCamera) {
  96272. return;
  96273. }
  96274. // Get rotation and position of the current camera
  96275. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  96276. var position = this.currentVRCamera.position;
  96277. // If the camera has device position, use that instead
  96278. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  96279. rotation = this.currentVRCamera.deviceRotationQuaternion;
  96280. position = this.currentVRCamera.devicePosition;
  96281. }
  96282. // Get matrix with only the y rotation of the device rotation
  96283. rotation.toEulerAnglesToRef(this._workingVector);
  96284. this._workingVector.z = 0;
  96285. this._workingVector.x = 0;
  96286. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  96287. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  96288. // Rotate backwards ray by device rotation to cast at the ground behind the user
  96289. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  96290. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  96291. var ray = new BABYLON.Ray(position, this._workingVector);
  96292. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96293. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  96294. this._teleportCamera(hit.pickedPoint);
  96295. }
  96296. gazer._teleportationBackRequestInitiated = true;
  96297. }
  96298. }
  96299. else {
  96300. gazer._teleportationBackRequestInitiated = false;
  96301. }
  96302. };
  96303. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  96304. var _this = this;
  96305. var controllerMesh = controller.webVRController.mesh;
  96306. if (controllerMesh) {
  96307. if (!controller._interactionsEnabled) {
  96308. this._enableInteractionOnController(controller);
  96309. }
  96310. controller._interactionsEnabled = true;
  96311. controller._teleportationEnabled = true;
  96312. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96313. controller._dpadPressed = false;
  96314. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  96315. controller._dpadPressed = stateObject.pressed;
  96316. if (!controller._dpadPressed) {
  96317. controller._rotationLeftAsked = false;
  96318. controller._rotationRightAsked = false;
  96319. controller._teleportationBackRequestInitiated = false;
  96320. }
  96321. });
  96322. }
  96323. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  96324. if (_this.teleportationEnabled) {
  96325. _this._checkTeleportBackwards(stateObject, controller);
  96326. _this._checkTeleportWithRay(stateObject, controller);
  96327. }
  96328. _this._checkRotate(stateObject, controller);
  96329. });
  96330. }
  96331. };
  96332. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  96333. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  96334. this._teleportationTarget.isPickable = false;
  96335. var length = 512;
  96336. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  96337. dynamicTexture.hasAlpha = true;
  96338. var context = dynamicTexture.getContext();
  96339. var centerX = length / 2;
  96340. var centerY = length / 2;
  96341. var radius = 200;
  96342. context.beginPath();
  96343. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  96344. context.fillStyle = this._teleportationFillColor;
  96345. context.fill();
  96346. context.lineWidth = 10;
  96347. context.strokeStyle = this._teleportationBorderColor;
  96348. context.stroke();
  96349. context.closePath();
  96350. dynamicTexture.update();
  96351. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96352. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96353. this._teleportationTarget.material = teleportationCircleMaterial;
  96354. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96355. torus.isPickable = false;
  96356. torus.parent = this._teleportationTarget;
  96357. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96358. var keys = [];
  96359. keys.push({
  96360. frame: 0,
  96361. value: 0
  96362. });
  96363. keys.push({
  96364. frame: 30,
  96365. value: 0.4
  96366. });
  96367. keys.push({
  96368. frame: 60,
  96369. value: 0
  96370. });
  96371. animationInnerCircle.setKeys(keys);
  96372. var easingFunction = new BABYLON.SineEase();
  96373. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96374. animationInnerCircle.setEasingFunction(easingFunction);
  96375. torus.animations = [];
  96376. torus.animations.push(animationInnerCircle);
  96377. this._scene.beginAnimation(torus, 0, 60, true);
  96378. this._hideTeleportationTarget();
  96379. };
  96380. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  96381. this._teleportActive = true;
  96382. if (this._teleportationInitialized) {
  96383. this._teleportationTarget.isVisible = true;
  96384. if (this._isDefaultTeleportationTarget) {
  96385. this._teleportationTarget.getChildren()[0].isVisible = true;
  96386. }
  96387. }
  96388. };
  96389. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  96390. this._teleportActive = false;
  96391. if (this._teleportationInitialized) {
  96392. this._teleportationTarget.isVisible = false;
  96393. if (this._isDefaultTeleportationTarget) {
  96394. this._teleportationTarget.getChildren()[0].isVisible = false;
  96395. }
  96396. }
  96397. };
  96398. VRExperienceHelper.prototype._rotateCamera = function (right) {
  96399. var _this = this;
  96400. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96401. return;
  96402. }
  96403. if (right) {
  96404. this._rotationAngle++;
  96405. }
  96406. else {
  96407. this._rotationAngle--;
  96408. }
  96409. this.currentVRCamera.animations = [];
  96410. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  96411. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96412. var animationRotationKeys = [];
  96413. animationRotationKeys.push({
  96414. frame: 0,
  96415. value: this.currentVRCamera.rotationQuaternion
  96416. });
  96417. animationRotationKeys.push({
  96418. frame: 6,
  96419. value: target
  96420. });
  96421. animationRotation.setKeys(animationRotationKeys);
  96422. animationRotation.setEasingFunction(this._circleEase);
  96423. this.currentVRCamera.animations.push(animationRotation);
  96424. this._postProcessMove.animations = [];
  96425. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96426. var vignetteWeightKeys = [];
  96427. vignetteWeightKeys.push({
  96428. frame: 0,
  96429. value: 0
  96430. });
  96431. vignetteWeightKeys.push({
  96432. frame: 3,
  96433. value: 4
  96434. });
  96435. vignetteWeightKeys.push({
  96436. frame: 6,
  96437. value: 0
  96438. });
  96439. animationPP.setKeys(vignetteWeightKeys);
  96440. animationPP.setEasingFunction(this._circleEase);
  96441. this._postProcessMove.animations.push(animationPP);
  96442. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96443. var vignetteStretchKeys = [];
  96444. vignetteStretchKeys.push({
  96445. frame: 0,
  96446. value: 0
  96447. });
  96448. vignetteStretchKeys.push({
  96449. frame: 3,
  96450. value: 10
  96451. });
  96452. vignetteStretchKeys.push({
  96453. frame: 6,
  96454. value: 0
  96455. });
  96456. animationPP2.setKeys(vignetteStretchKeys);
  96457. animationPP2.setEasingFunction(this._circleEase);
  96458. this._postProcessMove.animations.push(animationPP2);
  96459. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96460. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96461. this._postProcessMove.samples = 4;
  96462. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96463. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  96464. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96465. });
  96466. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  96467. };
  96468. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  96469. if (hit.pickedPoint) {
  96470. if (gazer._teleportationRequestInitiated) {
  96471. this._displayTeleportationTarget();
  96472. this._haloCenter.copyFrom(hit.pickedPoint);
  96473. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  96474. }
  96475. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  96476. if (pickNormal) {
  96477. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96478. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96479. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  96480. }
  96481. this._teleportationTarget.position.y += 0.1;
  96482. }
  96483. };
  96484. VRExperienceHelper.prototype._teleportCamera = function (location) {
  96485. var _this = this;
  96486. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96487. return;
  96488. }
  96489. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  96490. // offset of the headset from the anchor.
  96491. if (this.webVRCamera.leftCamera) {
  96492. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  96493. this._workingVector.subtractInPlace(this.webVRCamera.position);
  96494. location.subtractToRef(this._workingVector, this._workingVector);
  96495. }
  96496. else {
  96497. this._workingVector.copyFrom(location);
  96498. }
  96499. // Add height to account for user's height offset
  96500. if (this.isInVRMode) {
  96501. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  96502. }
  96503. else {
  96504. this._workingVector.y += this._defaultHeight;
  96505. }
  96506. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  96507. // Create animation from the camera's position to the new location
  96508. this.currentVRCamera.animations = [];
  96509. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96510. var animationCameraTeleportationKeys = [{
  96511. frame: 0,
  96512. value: this.currentVRCamera.position
  96513. },
  96514. {
  96515. frame: 11,
  96516. value: this._workingVector
  96517. }
  96518. ];
  96519. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  96520. animationCameraTeleportation.setEasingFunction(this._circleEase);
  96521. this.currentVRCamera.animations.push(animationCameraTeleportation);
  96522. this._postProcessMove.animations = [];
  96523. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96524. var vignetteWeightKeys = [];
  96525. vignetteWeightKeys.push({
  96526. frame: 0,
  96527. value: 0
  96528. });
  96529. vignetteWeightKeys.push({
  96530. frame: 5,
  96531. value: 8
  96532. });
  96533. vignetteWeightKeys.push({
  96534. frame: 11,
  96535. value: 0
  96536. });
  96537. animationPP.setKeys(vignetteWeightKeys);
  96538. this._postProcessMove.animations.push(animationPP);
  96539. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96540. var vignetteStretchKeys = [];
  96541. vignetteStretchKeys.push({
  96542. frame: 0,
  96543. value: 0
  96544. });
  96545. vignetteStretchKeys.push({
  96546. frame: 5,
  96547. value: 10
  96548. });
  96549. vignetteStretchKeys.push({
  96550. frame: 11,
  96551. value: 0
  96552. });
  96553. animationPP2.setKeys(vignetteStretchKeys);
  96554. this._postProcessMove.animations.push(animationPP2);
  96555. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96556. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96557. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96558. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  96559. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96560. });
  96561. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  96562. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  96563. });
  96564. this._hideTeleportationTarget();
  96565. };
  96566. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  96567. if (normal) {
  96568. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  96569. if (angle < Math.PI / 2) {
  96570. normal.scaleInPlace(-1);
  96571. }
  96572. }
  96573. return normal;
  96574. };
  96575. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  96576. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96577. return;
  96578. }
  96579. var ray = gazer._getForwardRay(this._rayLength);
  96580. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96581. if (hit) {
  96582. // Populate the contrllers mesh that can be used for drag/drop
  96583. if (gazer._laserPointer) {
  96584. hit.originMesh = gazer._laserPointer.parent;
  96585. }
  96586. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  96587. }
  96588. gazer._currentHit = hit;
  96589. // Moving the gazeTracker on the mesh face targetted
  96590. if (hit && hit.pickedPoint) {
  96591. if (this._displayGaze) {
  96592. var multiplier = 1;
  96593. gazer._gazeTracker.isVisible = true;
  96594. if (gazer._isActionableMesh) {
  96595. multiplier = 3;
  96596. }
  96597. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  96598. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  96599. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  96600. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  96601. // To avoid z-fighting
  96602. var deltaFighting = 0.002;
  96603. if (pickNormal) {
  96604. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96605. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96606. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  96607. }
  96608. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  96609. if (gazer._gazeTracker.position.x < 0) {
  96610. gazer._gazeTracker.position.x += deltaFighting;
  96611. }
  96612. else {
  96613. gazer._gazeTracker.position.x -= deltaFighting;
  96614. }
  96615. if (gazer._gazeTracker.position.y < 0) {
  96616. gazer._gazeTracker.position.y += deltaFighting;
  96617. }
  96618. else {
  96619. gazer._gazeTracker.position.y -= deltaFighting;
  96620. }
  96621. if (gazer._gazeTracker.position.z < 0) {
  96622. gazer._gazeTracker.position.z += deltaFighting;
  96623. }
  96624. else {
  96625. gazer._gazeTracker.position.z -= deltaFighting;
  96626. }
  96627. }
  96628. // Changing the size of the laser pointer based on the distance from the targetted point
  96629. gazer._updatePointerDistance(hit.distance);
  96630. }
  96631. else {
  96632. gazer._updatePointerDistance();
  96633. gazer._gazeTracker.isVisible = false;
  96634. }
  96635. if (hit && hit.pickedMesh) {
  96636. // The object selected is the floor, we're in a teleportation scenario
  96637. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  96638. // Moving the teleportation area to this targetted point
  96639. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  96640. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  96641. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  96642. }
  96643. gazer._currentMeshSelected = null;
  96644. if (gazer._teleportationRequestInitiated) {
  96645. this._moveTeleportationSelectorTo(hit, gazer, ray);
  96646. }
  96647. return;
  96648. }
  96649. // If not, we're in a selection scenario
  96650. //this._teleportationAllowed = false;
  96651. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  96652. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  96653. this.onNewMeshPicked.notifyObservers(hit);
  96654. gazer._currentMeshSelected = hit.pickedMesh;
  96655. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  96656. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  96657. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  96658. gazer._isActionableMesh = true;
  96659. }
  96660. else {
  96661. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96662. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96663. gazer._isActionableMesh = false;
  96664. }
  96665. try {
  96666. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  96667. }
  96668. catch (err) {
  96669. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  96670. }
  96671. }
  96672. else {
  96673. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  96674. gazer._currentMeshSelected = null;
  96675. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96676. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96677. }
  96678. }
  96679. }
  96680. else {
  96681. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  96682. gazer._currentMeshSelected = null;
  96683. //this._teleportationAllowed = false;
  96684. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96685. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96686. }
  96687. };
  96688. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  96689. if (mesh) {
  96690. this.onSelectedMeshUnselected.notifyObservers(mesh);
  96691. }
  96692. };
  96693. /**
  96694. * Sets the color of the laser ray from the vr controllers.
  96695. * @param color new color for the ray.
  96696. */
  96697. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  96698. if (this._leftController) {
  96699. this._leftController._setLaserPointerColor(color);
  96700. }
  96701. if (this._rightController) {
  96702. this._rightController._setLaserPointerColor(color);
  96703. }
  96704. };
  96705. /**
  96706. * Sets the color of the ray from the vr headsets gaze.
  96707. * @param color new color for the ray.
  96708. */
  96709. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  96710. if (!this._cameraGazer._gazeTracker.material) {
  96711. return;
  96712. }
  96713. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  96714. if (this._leftController) {
  96715. this._leftController._gazeTracker.material.emissiveColor = color;
  96716. }
  96717. if (this._rightController) {
  96718. this._rightController._gazeTracker.material.emissiveColor = color;
  96719. }
  96720. };
  96721. /**
  96722. * Exits VR and disposes of the vr experience helper
  96723. */
  96724. VRExperienceHelper.prototype.dispose = function () {
  96725. if (this.isInVRMode) {
  96726. this.exitVR();
  96727. }
  96728. if (this._postProcessMove) {
  96729. this._postProcessMove.dispose();
  96730. }
  96731. if (this._webVRCamera) {
  96732. this._webVRCamera.dispose();
  96733. }
  96734. if (this._vrDeviceOrientationCamera) {
  96735. this._vrDeviceOrientationCamera.dispose();
  96736. }
  96737. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  96738. document.body.removeChild(this._btnVR);
  96739. }
  96740. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  96741. this._deviceOrientationCamera.dispose();
  96742. }
  96743. if (this._cameraGazer) {
  96744. this._cameraGazer.dispose();
  96745. }
  96746. if (this._leftController) {
  96747. this._leftController.dispose();
  96748. }
  96749. if (this._rightController) {
  96750. this._rightController.dispose();
  96751. }
  96752. if (this._teleportationTarget) {
  96753. this._teleportationTarget.dispose();
  96754. }
  96755. this._floorMeshesCollection = [];
  96756. document.removeEventListener("keydown", this._onKeyDown);
  96757. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96758. window.removeEventListener("resize", this._onResize);
  96759. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  96760. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  96761. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  96762. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  96763. document.onmsfullscreenchange = null;
  96764. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  96765. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  96766. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  96767. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96768. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  96769. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  96770. this._scene.unregisterBeforeRender(this.beforeRender);
  96771. };
  96772. /**
  96773. * Gets the name of the VRExperienceHelper class
  96774. * @returns "VRExperienceHelper"
  96775. */
  96776. VRExperienceHelper.prototype.getClassName = function () {
  96777. return "VRExperienceHelper";
  96778. };
  96779. return VRExperienceHelper;
  96780. }());
  96781. BABYLON.VRExperienceHelper = VRExperienceHelper;
  96782. })(BABYLON || (BABYLON = {}));
  96783. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  96784. // Mainly based on these 2 articles :
  96785. // 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
  96786. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  96787. var BABYLON;
  96788. (function (BABYLON) {
  96789. /**
  96790. * Defines the potential axis of a Joystick
  96791. */
  96792. var JoystickAxis;
  96793. (function (JoystickAxis) {
  96794. /** X axis */
  96795. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  96796. /** Y axis */
  96797. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  96798. /** Z axis */
  96799. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  96800. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  96801. /**
  96802. * Class used to define virtual joystick (used in touch mode)
  96803. */
  96804. var VirtualJoystick = /** @class */ (function () {
  96805. /**
  96806. * Creates a new virtual joystick
  96807. * @param leftJoystick defines that the joystick is for left hand (false by default)
  96808. */
  96809. function VirtualJoystick(leftJoystick) {
  96810. var _this = this;
  96811. if (leftJoystick) {
  96812. this._leftJoystick = true;
  96813. }
  96814. else {
  96815. this._leftJoystick = false;
  96816. }
  96817. VirtualJoystick._globalJoystickIndex++;
  96818. // By default left & right arrow keys are moving the X
  96819. // and up & down keys are moving the Y
  96820. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  96821. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  96822. this.reverseLeftRight = false;
  96823. this.reverseUpDown = false;
  96824. // collections of pointers
  96825. this._touches = new BABYLON.StringDictionary();
  96826. this.deltaPosition = BABYLON.Vector3.Zero();
  96827. this._joystickSensibility = 25;
  96828. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  96829. this._onResize = function (evt) {
  96830. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  96831. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  96832. if (VirtualJoystick.vjCanvas) {
  96833. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  96834. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  96835. }
  96836. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  96837. };
  96838. // injecting a canvas element on top of the canvas 3D game
  96839. if (!VirtualJoystick.vjCanvas) {
  96840. window.addEventListener("resize", this._onResize, false);
  96841. VirtualJoystick.vjCanvas = document.createElement("canvas");
  96842. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  96843. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  96844. VirtualJoystick.vjCanvas.width = window.innerWidth;
  96845. VirtualJoystick.vjCanvas.height = window.innerHeight;
  96846. VirtualJoystick.vjCanvas.style.width = "100%";
  96847. VirtualJoystick.vjCanvas.style.height = "100%";
  96848. VirtualJoystick.vjCanvas.style.position = "absolute";
  96849. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  96850. VirtualJoystick.vjCanvas.style.top = "0px";
  96851. VirtualJoystick.vjCanvas.style.left = "0px";
  96852. VirtualJoystick.vjCanvas.style.zIndex = "5";
  96853. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  96854. // Support for jQuery PEP polyfill
  96855. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  96856. var context = VirtualJoystick.vjCanvas.getContext('2d');
  96857. if (!context) {
  96858. throw new Error("Unable to create canvas for virtual joystick");
  96859. }
  96860. VirtualJoystick.vjCanvasContext = context;
  96861. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  96862. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  96863. document.body.appendChild(VirtualJoystick.vjCanvas);
  96864. }
  96865. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  96866. this.pressed = false;
  96867. // default joystick color
  96868. this._joystickColor = "cyan";
  96869. this._joystickPointerID = -1;
  96870. // current joystick position
  96871. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  96872. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  96873. // origin joystick position
  96874. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  96875. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  96876. this._onPointerDownHandlerRef = function (evt) {
  96877. _this._onPointerDown(evt);
  96878. };
  96879. this._onPointerMoveHandlerRef = function (evt) {
  96880. _this._onPointerMove(evt);
  96881. };
  96882. this._onPointerUpHandlerRef = function (evt) {
  96883. _this._onPointerUp(evt);
  96884. };
  96885. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  96886. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  96887. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  96888. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  96889. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  96890. evt.preventDefault(); // Disables system menu
  96891. }, false);
  96892. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  96893. }
  96894. /**
  96895. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  96896. * @param newJoystickSensibility defines the new sensibility
  96897. */
  96898. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  96899. this._joystickSensibility = newJoystickSensibility;
  96900. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  96901. };
  96902. VirtualJoystick.prototype._onPointerDown = function (e) {
  96903. var positionOnScreenCondition;
  96904. e.preventDefault();
  96905. if (this._leftJoystick === true) {
  96906. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  96907. }
  96908. else {
  96909. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  96910. }
  96911. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  96912. // First contact will be dedicated to the virtual joystick
  96913. this._joystickPointerID = e.pointerId;
  96914. this._joystickPointerStartPos.x = e.clientX;
  96915. this._joystickPointerStartPos.y = e.clientY;
  96916. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  96917. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  96918. this._deltaJoystickVector.x = 0;
  96919. this._deltaJoystickVector.y = 0;
  96920. this.pressed = true;
  96921. this._touches.add(e.pointerId.toString(), e);
  96922. }
  96923. else {
  96924. // You can only trigger the action buttons with a joystick declared
  96925. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  96926. this._action();
  96927. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  96928. }
  96929. }
  96930. };
  96931. VirtualJoystick.prototype._onPointerMove = function (e) {
  96932. // If the current pointer is the one associated to the joystick (first touch contact)
  96933. if (this._joystickPointerID == e.pointerId) {
  96934. this._joystickPointerPos.x = e.clientX;
  96935. this._joystickPointerPos.y = e.clientY;
  96936. this._deltaJoystickVector = this._joystickPointerPos.clone();
  96937. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  96938. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  96939. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  96940. switch (this._axisTargetedByLeftAndRight) {
  96941. case JoystickAxis.X:
  96942. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  96943. break;
  96944. case JoystickAxis.Y:
  96945. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  96946. break;
  96947. case JoystickAxis.Z:
  96948. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  96949. break;
  96950. }
  96951. var directionUpDown = this.reverseUpDown ? 1 : -1;
  96952. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  96953. switch (this._axisTargetedByUpAndDown) {
  96954. case JoystickAxis.X:
  96955. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  96956. break;
  96957. case JoystickAxis.Y:
  96958. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  96959. break;
  96960. case JoystickAxis.Z:
  96961. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  96962. break;
  96963. }
  96964. }
  96965. else {
  96966. var data = this._touches.get(e.pointerId.toString());
  96967. if (data) {
  96968. data.x = e.clientX;
  96969. data.y = e.clientY;
  96970. }
  96971. }
  96972. };
  96973. VirtualJoystick.prototype._onPointerUp = function (e) {
  96974. if (this._joystickPointerID == e.pointerId) {
  96975. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  96976. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  96977. this._joystickPointerID = -1;
  96978. this.pressed = false;
  96979. }
  96980. else {
  96981. var touch = this._touches.get(e.pointerId.toString());
  96982. if (touch) {
  96983. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  96984. }
  96985. }
  96986. this._deltaJoystickVector.x = 0;
  96987. this._deltaJoystickVector.y = 0;
  96988. this._touches.remove(e.pointerId.toString());
  96989. };
  96990. /**
  96991. * Change the color of the virtual joystick
  96992. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  96993. */
  96994. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  96995. this._joystickColor = newColor;
  96996. };
  96997. /**
  96998. * Defines a callback to call when the joystick is touched
  96999. * @param action defines the callback
  97000. */
  97001. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  97002. this._action = action;
  97003. };
  97004. /**
  97005. * Defines which axis you'd like to control for left & right
  97006. * @param axis defines the axis to use
  97007. */
  97008. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  97009. switch (axis) {
  97010. case JoystickAxis.X:
  97011. case JoystickAxis.Y:
  97012. case JoystickAxis.Z:
  97013. this._axisTargetedByLeftAndRight = axis;
  97014. break;
  97015. default:
  97016. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97017. break;
  97018. }
  97019. };
  97020. /**
  97021. * Defines which axis you'd like to control for up & down
  97022. * @param axis defines the axis to use
  97023. */
  97024. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  97025. switch (axis) {
  97026. case JoystickAxis.X:
  97027. case JoystickAxis.Y:
  97028. case JoystickAxis.Z:
  97029. this._axisTargetedByUpAndDown = axis;
  97030. break;
  97031. default:
  97032. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97033. break;
  97034. }
  97035. };
  97036. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  97037. var _this = this;
  97038. if (this.pressed) {
  97039. this._touches.forEach(function (key, touch) {
  97040. if (touch.pointerId === _this._joystickPointerID) {
  97041. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  97042. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  97043. VirtualJoystick.vjCanvasContext.beginPath();
  97044. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97045. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97046. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  97047. VirtualJoystick.vjCanvasContext.stroke();
  97048. VirtualJoystick.vjCanvasContext.closePath();
  97049. VirtualJoystick.vjCanvasContext.beginPath();
  97050. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97051. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97052. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  97053. VirtualJoystick.vjCanvasContext.stroke();
  97054. VirtualJoystick.vjCanvasContext.closePath();
  97055. VirtualJoystick.vjCanvasContext.beginPath();
  97056. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97057. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  97058. VirtualJoystick.vjCanvasContext.stroke();
  97059. VirtualJoystick.vjCanvasContext.closePath();
  97060. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  97061. }
  97062. else {
  97063. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97064. VirtualJoystick.vjCanvasContext.beginPath();
  97065. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  97066. VirtualJoystick.vjCanvasContext.beginPath();
  97067. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  97068. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97069. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  97070. VirtualJoystick.vjCanvasContext.stroke();
  97071. VirtualJoystick.vjCanvasContext.closePath();
  97072. touch.prevX = touch.x;
  97073. touch.prevY = touch.y;
  97074. }
  97075. ;
  97076. });
  97077. }
  97078. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97079. };
  97080. /**
  97081. * Release internal HTML canvas
  97082. */
  97083. VirtualJoystick.prototype.releaseCanvas = function () {
  97084. if (VirtualJoystick.vjCanvas) {
  97085. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  97086. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  97087. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  97088. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  97089. window.removeEventListener("resize", this._onResize);
  97090. document.body.removeChild(VirtualJoystick.vjCanvas);
  97091. VirtualJoystick.vjCanvas = null;
  97092. }
  97093. };
  97094. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  97095. VirtualJoystick._globalJoystickIndex = 0;
  97096. return VirtualJoystick;
  97097. }());
  97098. BABYLON.VirtualJoystick = VirtualJoystick;
  97099. })(BABYLON || (BABYLON = {}));
  97100. //# sourceMappingURL=babylon.virtualJoystick.js.map
  97101. var BABYLON;
  97102. (function (BABYLON) {
  97103. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  97104. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  97105. });
  97106. // We're mainly based on the logic defined into the FreeCamera code
  97107. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  97108. __extends(VirtualJoysticksCamera, _super);
  97109. function VirtualJoysticksCamera(name, position, scene) {
  97110. var _this = _super.call(this, name, position, scene) || this;
  97111. _this.inputs.addVirtualJoystick();
  97112. return _this;
  97113. }
  97114. VirtualJoysticksCamera.prototype.getClassName = function () {
  97115. return "VirtualJoysticksCamera";
  97116. };
  97117. return VirtualJoysticksCamera;
  97118. }(BABYLON.FreeCamera));
  97119. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  97120. })(BABYLON || (BABYLON = {}));
  97121. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  97122. var BABYLON;
  97123. (function (BABYLON) {
  97124. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  97125. function FreeCameraVirtualJoystickInput() {
  97126. }
  97127. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  97128. return this._leftjoystick;
  97129. };
  97130. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  97131. return this._rightjoystick;
  97132. };
  97133. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  97134. if (this._leftjoystick) {
  97135. var camera = this.camera;
  97136. var speed = camera._computeLocalCameraSpeed() * 50;
  97137. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  97138. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  97139. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  97140. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  97141. if (!this._leftjoystick.pressed) {
  97142. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  97143. }
  97144. if (!this._rightjoystick.pressed) {
  97145. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  97146. }
  97147. }
  97148. };
  97149. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  97150. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  97151. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  97152. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  97153. this._leftjoystick.setJoystickSensibility(0.15);
  97154. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  97155. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  97156. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  97157. this._rightjoystick.reverseUpDown = true;
  97158. this._rightjoystick.setJoystickSensibility(0.05);
  97159. this._rightjoystick.setJoystickColor("yellow");
  97160. };
  97161. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  97162. this._leftjoystick.releaseCanvas();
  97163. this._rightjoystick.releaseCanvas();
  97164. };
  97165. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  97166. return "FreeCameraVirtualJoystickInput";
  97167. };
  97168. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  97169. return "virtualJoystick";
  97170. };
  97171. return FreeCameraVirtualJoystickInput;
  97172. }());
  97173. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  97174. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  97175. })(BABYLON || (BABYLON = {}));
  97176. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  97177. var BABYLON;
  97178. (function (BABYLON) {
  97179. var SimplificationSettings = /** @class */ (function () {
  97180. function SimplificationSettings(quality, distance, optimizeMesh) {
  97181. this.quality = quality;
  97182. this.distance = distance;
  97183. this.optimizeMesh = optimizeMesh;
  97184. }
  97185. return SimplificationSettings;
  97186. }());
  97187. BABYLON.SimplificationSettings = SimplificationSettings;
  97188. var SimplificationQueue = /** @class */ (function () {
  97189. function SimplificationQueue() {
  97190. this.running = false;
  97191. this._simplificationArray = [];
  97192. }
  97193. SimplificationQueue.prototype.addTask = function (task) {
  97194. this._simplificationArray.push(task);
  97195. };
  97196. SimplificationQueue.prototype.executeNext = function () {
  97197. var task = this._simplificationArray.pop();
  97198. if (task) {
  97199. this.running = true;
  97200. this.runSimplification(task);
  97201. }
  97202. else {
  97203. this.running = false;
  97204. }
  97205. };
  97206. SimplificationQueue.prototype.runSimplification = function (task) {
  97207. var _this = this;
  97208. if (task.parallelProcessing) {
  97209. //parallel simplifier
  97210. task.settings.forEach(function (setting) {
  97211. var simplifier = _this.getSimplifier(task);
  97212. simplifier.simplify(setting, function (newMesh) {
  97213. task.mesh.addLODLevel(setting.distance, newMesh);
  97214. newMesh.isVisible = true;
  97215. //check if it is the last
  97216. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  97217. //all done, run the success callback.
  97218. task.successCallback();
  97219. }
  97220. _this.executeNext();
  97221. });
  97222. });
  97223. }
  97224. else {
  97225. //single simplifier.
  97226. var simplifier = this.getSimplifier(task);
  97227. var runDecimation = function (setting, callback) {
  97228. simplifier.simplify(setting, function (newMesh) {
  97229. task.mesh.addLODLevel(setting.distance, newMesh);
  97230. newMesh.isVisible = true;
  97231. //run the next quality level
  97232. callback();
  97233. });
  97234. };
  97235. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  97236. runDecimation(task.settings[loop.index], function () {
  97237. loop.executeNext();
  97238. });
  97239. }, function () {
  97240. //execution ended, run the success callback.
  97241. if (task.successCallback) {
  97242. task.successCallback();
  97243. }
  97244. _this.executeNext();
  97245. });
  97246. }
  97247. };
  97248. SimplificationQueue.prototype.getSimplifier = function (task) {
  97249. switch (task.simplificationType) {
  97250. case SimplificationType.QUADRATIC:
  97251. default:
  97252. return new QuadraticErrorSimplification(task.mesh);
  97253. }
  97254. };
  97255. return SimplificationQueue;
  97256. }());
  97257. BABYLON.SimplificationQueue = SimplificationQueue;
  97258. /**
  97259. * The implemented types of simplification
  97260. * At the moment only Quadratic Error Decimation is implemented
  97261. */
  97262. var SimplificationType;
  97263. (function (SimplificationType) {
  97264. /** Quadratic error decimation */
  97265. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  97266. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  97267. var DecimationTriangle = /** @class */ (function () {
  97268. function DecimationTriangle(vertices) {
  97269. this.vertices = vertices;
  97270. this.error = new Array(4);
  97271. this.deleted = false;
  97272. this.isDirty = false;
  97273. this.deletePending = false;
  97274. this.borderFactor = 0;
  97275. }
  97276. return DecimationTriangle;
  97277. }());
  97278. BABYLON.DecimationTriangle = DecimationTriangle;
  97279. var DecimationVertex = /** @class */ (function () {
  97280. function DecimationVertex(position, id) {
  97281. this.position = position;
  97282. this.id = id;
  97283. this.isBorder = true;
  97284. this.q = new QuadraticMatrix();
  97285. this.triangleCount = 0;
  97286. this.triangleStart = 0;
  97287. this.originalOffsets = [];
  97288. }
  97289. DecimationVertex.prototype.updatePosition = function (newPosition) {
  97290. this.position.copyFrom(newPosition);
  97291. };
  97292. return DecimationVertex;
  97293. }());
  97294. BABYLON.DecimationVertex = DecimationVertex;
  97295. var QuadraticMatrix = /** @class */ (function () {
  97296. function QuadraticMatrix(data) {
  97297. this.data = new Array(10);
  97298. for (var i = 0; i < 10; ++i) {
  97299. if (data && data[i]) {
  97300. this.data[i] = data[i];
  97301. }
  97302. else {
  97303. this.data[i] = 0;
  97304. }
  97305. }
  97306. }
  97307. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  97308. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  97309. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  97310. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  97311. return det;
  97312. };
  97313. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  97314. for (var i = 0; i < 10; ++i) {
  97315. this.data[i] += matrix.data[i];
  97316. }
  97317. };
  97318. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  97319. for (var i = 0; i < 10; ++i) {
  97320. this.data[i] += data[i];
  97321. }
  97322. };
  97323. QuadraticMatrix.prototype.add = function (matrix) {
  97324. var m = new QuadraticMatrix();
  97325. for (var i = 0; i < 10; ++i) {
  97326. m.data[i] = this.data[i] + matrix.data[i];
  97327. }
  97328. return m;
  97329. };
  97330. QuadraticMatrix.FromData = function (a, b, c, d) {
  97331. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  97332. };
  97333. //returning an array to avoid garbage collection
  97334. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  97335. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  97336. };
  97337. return QuadraticMatrix;
  97338. }());
  97339. BABYLON.QuadraticMatrix = QuadraticMatrix;
  97340. var Reference = /** @class */ (function () {
  97341. function Reference(vertexId, triangleId) {
  97342. this.vertexId = vertexId;
  97343. this.triangleId = triangleId;
  97344. }
  97345. return Reference;
  97346. }());
  97347. BABYLON.Reference = Reference;
  97348. /**
  97349. * An implementation of the Quadratic Error simplification algorithm.
  97350. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97351. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97352. * @author RaananW
  97353. */
  97354. var QuadraticErrorSimplification = /** @class */ (function () {
  97355. function QuadraticErrorSimplification(_mesh) {
  97356. this._mesh = _mesh;
  97357. this.syncIterations = 5000;
  97358. this.aggressiveness = 7;
  97359. this.decimationIterations = 100;
  97360. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97361. }
  97362. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  97363. var _this = this;
  97364. this.initDecimatedMesh();
  97365. //iterating through the submeshes array, one after the other.
  97366. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  97367. _this.initWithMesh(loop.index, function () {
  97368. _this.runDecimation(settings, loop.index, function () {
  97369. loop.executeNext();
  97370. });
  97371. }, settings.optimizeMesh);
  97372. }, function () {
  97373. setTimeout(function () {
  97374. successCallback(_this._reconstructedMesh);
  97375. }, 0);
  97376. });
  97377. };
  97378. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  97379. var _this = this;
  97380. var targetCount = ~~(this.triangles.length * settings.quality);
  97381. var deletedTriangles = 0;
  97382. var triangleCount = this.triangles.length;
  97383. var iterationFunction = function (iteration, callback) {
  97384. setTimeout(function () {
  97385. if (iteration % 5 === 0) {
  97386. _this.updateMesh(iteration === 0);
  97387. }
  97388. for (var i = 0; i < _this.triangles.length; ++i) {
  97389. _this.triangles[i].isDirty = false;
  97390. }
  97391. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  97392. var trianglesIterator = function (i) {
  97393. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  97394. var t = _this.triangles[tIdx];
  97395. if (!t)
  97396. return;
  97397. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  97398. return;
  97399. }
  97400. for (var j = 0; j < 3; ++j) {
  97401. if (t.error[j] < threshold) {
  97402. var deleted0 = [];
  97403. var deleted1 = [];
  97404. var v0 = t.vertices[j];
  97405. var v1 = t.vertices[(j + 1) % 3];
  97406. if (v0.isBorder || v1.isBorder)
  97407. continue;
  97408. var p = BABYLON.Vector3.Zero();
  97409. var n = BABYLON.Vector3.Zero();
  97410. var uv = BABYLON.Vector2.Zero();
  97411. var color = new BABYLON.Color4(0, 0, 0, 1);
  97412. _this.calculateError(v0, v1, p, n, uv, color);
  97413. var delTr = new Array();
  97414. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  97415. continue;
  97416. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  97417. continue;
  97418. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  97419. continue;
  97420. var uniqueArray = new Array();
  97421. delTr.forEach(function (deletedT) {
  97422. if (uniqueArray.indexOf(deletedT) === -1) {
  97423. deletedT.deletePending = true;
  97424. uniqueArray.push(deletedT);
  97425. }
  97426. });
  97427. if (uniqueArray.length % 2 !== 0) {
  97428. continue;
  97429. }
  97430. v0.q = v1.q.add(v0.q);
  97431. v0.updatePosition(p);
  97432. var tStart = _this.references.length;
  97433. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  97434. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  97435. var tCount = _this.references.length - tStart;
  97436. if (tCount <= v0.triangleCount) {
  97437. if (tCount) {
  97438. for (var c = 0; c < tCount; c++) {
  97439. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  97440. }
  97441. }
  97442. }
  97443. else {
  97444. v0.triangleStart = tStart;
  97445. }
  97446. v0.triangleCount = tCount;
  97447. break;
  97448. }
  97449. }
  97450. };
  97451. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  97452. }, 0);
  97453. };
  97454. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  97455. if (triangleCount - deletedTriangles <= targetCount)
  97456. loop.breakLoop();
  97457. else {
  97458. iterationFunction(loop.index, function () {
  97459. loop.executeNext();
  97460. });
  97461. }
  97462. }, function () {
  97463. setTimeout(function () {
  97464. //reconstruct this part of the mesh
  97465. _this.reconstructMesh(submeshIndex);
  97466. successCallback();
  97467. }, 0);
  97468. });
  97469. };
  97470. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  97471. var _this = this;
  97472. this.vertices = [];
  97473. this.triangles = [];
  97474. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97475. var indices = this._mesh.getIndices();
  97476. var submesh = this._mesh.subMeshes[submeshIndex];
  97477. var findInVertices = function (positionToSearch) {
  97478. if (optimizeMesh) {
  97479. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  97480. if (_this.vertices[ii].position.equals(positionToSearch)) {
  97481. return _this.vertices[ii];
  97482. }
  97483. }
  97484. }
  97485. return null;
  97486. };
  97487. var vertexReferences = [];
  97488. var vertexInit = function (i) {
  97489. if (!positionData) {
  97490. return;
  97491. }
  97492. var offset = i + submesh.verticesStart;
  97493. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  97494. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  97495. vertex.originalOffsets.push(offset);
  97496. if (vertex.id === _this.vertices.length) {
  97497. _this.vertices.push(vertex);
  97498. }
  97499. vertexReferences.push(vertex.id);
  97500. };
  97501. //var totalVertices = mesh.getTotalVertices();
  97502. var totalVertices = submesh.verticesCount;
  97503. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  97504. var indicesInit = function (i) {
  97505. if (!indices) {
  97506. return;
  97507. }
  97508. var offset = (submesh.indexStart / 3) + i;
  97509. var pos = (offset * 3);
  97510. var i0 = indices[pos + 0];
  97511. var i1 = indices[pos + 1];
  97512. var i2 = indices[pos + 2];
  97513. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  97514. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  97515. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  97516. var triangle = new DecimationTriangle([v0, v1, v2]);
  97517. triangle.originalOffset = pos;
  97518. _this.triangles.push(triangle);
  97519. };
  97520. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  97521. _this.init(callback);
  97522. });
  97523. });
  97524. };
  97525. QuadraticErrorSimplification.prototype.init = function (callback) {
  97526. var _this = this;
  97527. var triangleInit1 = function (i) {
  97528. var t = _this.triangles[i];
  97529. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  97530. for (var j = 0; j < 3; j++) {
  97531. 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))));
  97532. }
  97533. };
  97534. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  97535. var triangleInit2 = function (i) {
  97536. var t = _this.triangles[i];
  97537. for (var j = 0; j < 3; ++j) {
  97538. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  97539. }
  97540. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97541. };
  97542. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  97543. callback();
  97544. });
  97545. });
  97546. };
  97547. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  97548. var newTriangles = [];
  97549. var i;
  97550. for (i = 0; i < this.vertices.length; ++i) {
  97551. this.vertices[i].triangleCount = 0;
  97552. }
  97553. var t;
  97554. var j;
  97555. for (i = 0; i < this.triangles.length; ++i) {
  97556. if (!this.triangles[i].deleted) {
  97557. t = this.triangles[i];
  97558. for (j = 0; j < 3; ++j) {
  97559. t.vertices[j].triangleCount = 1;
  97560. }
  97561. newTriangles.push(t);
  97562. }
  97563. }
  97564. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  97565. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  97566. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  97567. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  97568. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  97569. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  97570. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  97571. var vertexCount = 0;
  97572. for (i = 0; i < this.vertices.length; ++i) {
  97573. var vertex = this.vertices[i];
  97574. vertex.id = vertexCount;
  97575. if (vertex.triangleCount) {
  97576. vertex.originalOffsets.forEach(function (originalOffset) {
  97577. if (!normalData) {
  97578. return;
  97579. }
  97580. newPositionData.push(vertex.position.x);
  97581. newPositionData.push(vertex.position.y);
  97582. newPositionData.push(vertex.position.z);
  97583. newNormalData.push(normalData[originalOffset * 3]);
  97584. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  97585. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  97586. if (uvs && uvs.length) {
  97587. newUVsData.push(uvs[(originalOffset * 2)]);
  97588. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  97589. }
  97590. else if (colorsData && colorsData.length) {
  97591. newColorsData.push(colorsData[(originalOffset * 4)]);
  97592. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  97593. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  97594. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  97595. }
  97596. ++vertexCount;
  97597. });
  97598. }
  97599. }
  97600. var startingIndex = this._reconstructedMesh.getTotalIndices();
  97601. var startingVertex = this._reconstructedMesh.getTotalVertices();
  97602. var submeshesArray = this._reconstructedMesh.subMeshes;
  97603. this._reconstructedMesh.subMeshes = [];
  97604. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  97605. var originalIndices = this._mesh.getIndices();
  97606. for (i = 0; i < newTriangles.length; ++i) {
  97607. t = newTriangles[i]; //now get the new referencing point for each vertex
  97608. [0, 1, 2].forEach(function (idx) {
  97609. var id = originalIndices[t.originalOffset + idx];
  97610. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  97611. if (offset < 0)
  97612. offset = 0;
  97613. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  97614. });
  97615. }
  97616. //overwriting the old vertex buffers and indices.
  97617. this._reconstructedMesh.setIndices(newIndicesArray);
  97618. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  97619. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  97620. if (newUVsData.length > 0)
  97621. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  97622. if (newColorsData.length > 0)
  97623. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  97624. //create submesh
  97625. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  97626. if (submeshIndex > 0) {
  97627. this._reconstructedMesh.subMeshes = [];
  97628. submeshesArray.forEach(function (submesh) {
  97629. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  97630. });
  97631. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  97632. }
  97633. };
  97634. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  97635. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  97636. this._reconstructedMesh.material = this._mesh.material;
  97637. this._reconstructedMesh.parent = this._mesh.parent;
  97638. this._reconstructedMesh.isVisible = false;
  97639. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  97640. };
  97641. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  97642. for (var i = 0; i < vertex1.triangleCount; ++i) {
  97643. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  97644. if (t.deleted)
  97645. continue;
  97646. var s = this.references[vertex1.triangleStart + i].vertexId;
  97647. var v1 = t.vertices[(s + 1) % 3];
  97648. var v2 = t.vertices[(s + 2) % 3];
  97649. if ((v1 === vertex2 || v2 === vertex2)) {
  97650. deletedArray[i] = true;
  97651. delTr.push(t);
  97652. continue;
  97653. }
  97654. var d1 = v1.position.subtract(point);
  97655. d1 = d1.normalize();
  97656. var d2 = v2.position.subtract(point);
  97657. d2 = d2.normalize();
  97658. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  97659. return true;
  97660. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  97661. deletedArray[i] = false;
  97662. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  97663. return true;
  97664. }
  97665. return false;
  97666. };
  97667. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  97668. var newDeleted = deletedTriangles;
  97669. for (var i = 0; i < vertex.triangleCount; ++i) {
  97670. var ref = this.references[vertex.triangleStart + i];
  97671. var t = this.triangles[ref.triangleId];
  97672. if (t.deleted)
  97673. continue;
  97674. if (deletedArray[i] && t.deletePending) {
  97675. t.deleted = true;
  97676. newDeleted++;
  97677. continue;
  97678. }
  97679. t.vertices[ref.vertexId] = origVertex;
  97680. t.isDirty = true;
  97681. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  97682. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  97683. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  97684. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97685. this.references.push(ref);
  97686. }
  97687. return newDeleted;
  97688. };
  97689. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  97690. for (var i = 0; i < this.vertices.length; ++i) {
  97691. var vCount = [];
  97692. var vId = [];
  97693. var v = this.vertices[i];
  97694. var j;
  97695. for (j = 0; j < v.triangleCount; ++j) {
  97696. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  97697. for (var ii = 0; ii < 3; ii++) {
  97698. var ofs = 0;
  97699. var vv = triangle.vertices[ii];
  97700. while (ofs < vCount.length) {
  97701. if (vId[ofs] === vv.id)
  97702. break;
  97703. ++ofs;
  97704. }
  97705. if (ofs === vCount.length) {
  97706. vCount.push(1);
  97707. vId.push(vv.id);
  97708. }
  97709. else {
  97710. vCount[ofs]++;
  97711. }
  97712. }
  97713. }
  97714. for (j = 0; j < vCount.length; ++j) {
  97715. if (vCount[j] === 1) {
  97716. this.vertices[vId[j]].isBorder = true;
  97717. }
  97718. else {
  97719. this.vertices[vId[j]].isBorder = false;
  97720. }
  97721. }
  97722. }
  97723. };
  97724. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  97725. if (identifyBorders === void 0) { identifyBorders = false; }
  97726. var i;
  97727. if (!identifyBorders) {
  97728. var newTrianglesVector = [];
  97729. for (i = 0; i < this.triangles.length; ++i) {
  97730. if (!this.triangles[i].deleted) {
  97731. newTrianglesVector.push(this.triangles[i]);
  97732. }
  97733. }
  97734. this.triangles = newTrianglesVector;
  97735. }
  97736. for (i = 0; i < this.vertices.length; ++i) {
  97737. this.vertices[i].triangleCount = 0;
  97738. this.vertices[i].triangleStart = 0;
  97739. }
  97740. var t;
  97741. var j;
  97742. var v;
  97743. for (i = 0; i < this.triangles.length; ++i) {
  97744. t = this.triangles[i];
  97745. for (j = 0; j < 3; ++j) {
  97746. v = t.vertices[j];
  97747. v.triangleCount++;
  97748. }
  97749. }
  97750. var tStart = 0;
  97751. for (i = 0; i < this.vertices.length; ++i) {
  97752. this.vertices[i].triangleStart = tStart;
  97753. tStart += this.vertices[i].triangleCount;
  97754. this.vertices[i].triangleCount = 0;
  97755. }
  97756. var newReferences = new Array(this.triangles.length * 3);
  97757. for (i = 0; i < this.triangles.length; ++i) {
  97758. t = this.triangles[i];
  97759. for (j = 0; j < 3; ++j) {
  97760. v = t.vertices[j];
  97761. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  97762. v.triangleCount++;
  97763. }
  97764. }
  97765. this.references = newReferences;
  97766. if (identifyBorders) {
  97767. this.identifyBorder();
  97768. }
  97769. };
  97770. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  97771. var x = point.x;
  97772. var y = point.y;
  97773. var z = point.z;
  97774. 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
  97775. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  97776. };
  97777. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  97778. var q = vertex1.q.add(vertex2.q);
  97779. var border = vertex1.isBorder && vertex2.isBorder;
  97780. var error = 0;
  97781. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  97782. if (qDet !== 0 && !border) {
  97783. if (!pointResult) {
  97784. pointResult = BABYLON.Vector3.Zero();
  97785. }
  97786. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  97787. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  97788. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  97789. error = this.vertexError(q, pointResult);
  97790. }
  97791. else {
  97792. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  97793. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  97794. var error1 = this.vertexError(q, vertex1.position);
  97795. var error2 = this.vertexError(q, vertex2.position);
  97796. var error3 = this.vertexError(q, p3);
  97797. error = Math.min(error1, error2, error3);
  97798. if (error === error1) {
  97799. if (pointResult) {
  97800. pointResult.copyFrom(vertex1.position);
  97801. }
  97802. }
  97803. else if (error === error2) {
  97804. if (pointResult) {
  97805. pointResult.copyFrom(vertex2.position);
  97806. }
  97807. }
  97808. else {
  97809. if (pointResult) {
  97810. pointResult.copyFrom(p3);
  97811. }
  97812. }
  97813. }
  97814. return error;
  97815. };
  97816. return QuadraticErrorSimplification;
  97817. }());
  97818. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  97819. })(BABYLON || (BABYLON = {}));
  97820. //# sourceMappingURL=babylon.meshSimplification.js.map
  97821. var BABYLON;
  97822. (function (BABYLON) {
  97823. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  97824. get: function () {
  97825. if (!this._simplificationQueue) {
  97826. this._simplificationQueue = new BABYLON.SimplificationQueue();
  97827. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  97828. if (!component) {
  97829. component = new SimplicationQueueSceneComponent(this);
  97830. this._addComponent(component);
  97831. }
  97832. }
  97833. return this._simplificationQueue;
  97834. },
  97835. set: function (value) {
  97836. this._simplificationQueue = value;
  97837. },
  97838. enumerable: true,
  97839. configurable: true
  97840. });
  97841. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  97842. if (parallelProcessing === void 0) { parallelProcessing = true; }
  97843. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  97844. this.getScene().simplificationQueue.addTask({
  97845. settings: settings,
  97846. parallelProcessing: parallelProcessing,
  97847. mesh: this,
  97848. simplificationType: simplificationType,
  97849. successCallback: successCallback
  97850. });
  97851. return this;
  97852. };
  97853. /**
  97854. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  97855. * created in a scene
  97856. */
  97857. var SimplicationQueueSceneComponent = /** @class */ (function () {
  97858. /**
  97859. * Creates a new instance of the component for the given scene
  97860. * @param scene Defines the scene to register the component in
  97861. */
  97862. function SimplicationQueueSceneComponent(scene) {
  97863. /**
  97864. * The component name helpfull to identify the component in the list of scene components.
  97865. */
  97866. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  97867. this.scene = scene;
  97868. }
  97869. /**
  97870. * Registers the component in a given scene
  97871. */
  97872. SimplicationQueueSceneComponent.prototype.register = function () {
  97873. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  97874. };
  97875. /**
  97876. * Rebuilds the elements related to this component in case of
  97877. * context lost for instance.
  97878. */
  97879. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  97880. // Nothing to do for this component
  97881. };
  97882. /**
  97883. * Disposes the component and the associated ressources
  97884. */
  97885. SimplicationQueueSceneComponent.prototype.dispose = function () {
  97886. // Nothing to do for this component
  97887. };
  97888. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  97889. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  97890. this.scene._simplificationQueue.executeNext();
  97891. }
  97892. };
  97893. return SimplicationQueueSceneComponent;
  97894. }());
  97895. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  97896. })(BABYLON || (BABYLON = {}));
  97897. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  97898. var BABYLON;
  97899. (function (BABYLON) {
  97900. var MeshLODLevel = /** @class */ (function () {
  97901. function MeshLODLevel(distance, mesh) {
  97902. this.distance = distance;
  97903. this.mesh = mesh;
  97904. }
  97905. return MeshLODLevel;
  97906. }());
  97907. BABYLON.MeshLODLevel = MeshLODLevel;
  97908. })(BABYLON || (BABYLON = {}));
  97909. //# sourceMappingURL=babylon.meshLODLevel.js.map
  97910. var BABYLON;
  97911. (function (BABYLON) {
  97912. /**
  97913. * Defines the root class used to create scene optimization to use with SceneOptimizer
  97914. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97915. */
  97916. var SceneOptimization = /** @class */ (function () {
  97917. /**
  97918. * Creates the SceneOptimization object
  97919. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97920. * @param desc defines the description associated with the optimization
  97921. */
  97922. function SceneOptimization(
  97923. /**
  97924. * Defines the priority of this optimization (0 by default which means first in the list)
  97925. */
  97926. priority) {
  97927. if (priority === void 0) { priority = 0; }
  97928. this.priority = priority;
  97929. }
  97930. /**
  97931. * Gets a string describing the action executed by the current optimization
  97932. * @returns description string
  97933. */
  97934. SceneOptimization.prototype.getDescription = function () {
  97935. return "";
  97936. };
  97937. /**
  97938. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97939. * @param scene defines the current scene where to apply this optimization
  97940. * @param optimizer defines the current optimizer
  97941. * @returns true if everything that can be done was applied
  97942. */
  97943. SceneOptimization.prototype.apply = function (scene, optimizer) {
  97944. return true;
  97945. };
  97946. ;
  97947. return SceneOptimization;
  97948. }());
  97949. BABYLON.SceneOptimization = SceneOptimization;
  97950. /**
  97951. * Defines an optimization used to reduce the size of render target textures
  97952. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97953. */
  97954. var TextureOptimization = /** @class */ (function (_super) {
  97955. __extends(TextureOptimization, _super);
  97956. /**
  97957. * Creates the TextureOptimization object
  97958. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97959. * @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
  97960. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  97961. */
  97962. function TextureOptimization(
  97963. /**
  97964. * Defines the priority of this optimization (0 by default which means first in the list)
  97965. */
  97966. priority,
  97967. /**
  97968. * 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
  97969. */
  97970. maximumSize,
  97971. /**
  97972. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  97973. */
  97974. step) {
  97975. if (priority === void 0) { priority = 0; }
  97976. if (maximumSize === void 0) { maximumSize = 1024; }
  97977. if (step === void 0) { step = 0.5; }
  97978. var _this = _super.call(this, priority) || this;
  97979. _this.priority = priority;
  97980. _this.maximumSize = maximumSize;
  97981. _this.step = step;
  97982. return _this;
  97983. }
  97984. /**
  97985. * Gets a string describing the action executed by the current optimization
  97986. * @returns description string
  97987. */
  97988. TextureOptimization.prototype.getDescription = function () {
  97989. return "Reducing render target texture size to " + this.maximumSize;
  97990. };
  97991. /**
  97992. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97993. * @param scene defines the current scene where to apply this optimization
  97994. * @param optimizer defines the current optimizer
  97995. * @returns true if everything that can be done was applied
  97996. */
  97997. TextureOptimization.prototype.apply = function (scene, optimizer) {
  97998. var allDone = true;
  97999. for (var index = 0; index < scene.textures.length; index++) {
  98000. var texture = scene.textures[index];
  98001. if (!texture.canRescale || texture.getContext) {
  98002. continue;
  98003. }
  98004. var currentSize = texture.getSize();
  98005. var maxDimension = Math.max(currentSize.width, currentSize.height);
  98006. if (maxDimension > this.maximumSize) {
  98007. texture.scale(this.step);
  98008. allDone = false;
  98009. }
  98010. }
  98011. return allDone;
  98012. };
  98013. return TextureOptimization;
  98014. }(SceneOptimization));
  98015. BABYLON.TextureOptimization = TextureOptimization;
  98016. /**
  98017. * Defines an optimization used to increase or decrease the rendering resolution
  98018. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98019. */
  98020. var HardwareScalingOptimization = /** @class */ (function (_super) {
  98021. __extends(HardwareScalingOptimization, _super);
  98022. /**
  98023. * Creates the HardwareScalingOptimization object
  98024. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98025. * @param maximumScale defines the maximum scale to use (2 by default)
  98026. * @param step defines the step to use between two passes (0.5 by default)
  98027. */
  98028. function HardwareScalingOptimization(
  98029. /**
  98030. * Defines the priority of this optimization (0 by default which means first in the list)
  98031. */
  98032. priority,
  98033. /**
  98034. * Defines the maximum scale to use (2 by default)
  98035. */
  98036. maximumScale,
  98037. /**
  98038. * Defines the step to use between two passes (0.5 by default)
  98039. */
  98040. step) {
  98041. if (priority === void 0) { priority = 0; }
  98042. if (maximumScale === void 0) { maximumScale = 2; }
  98043. if (step === void 0) { step = 0.25; }
  98044. var _this = _super.call(this, priority) || this;
  98045. _this.priority = priority;
  98046. _this.maximumScale = maximumScale;
  98047. _this.step = step;
  98048. _this._currentScale = -1;
  98049. _this._directionOffset = 1;
  98050. return _this;
  98051. }
  98052. /**
  98053. * Gets a string describing the action executed by the current optimization
  98054. * @return description string
  98055. */
  98056. HardwareScalingOptimization.prototype.getDescription = function () {
  98057. return "Setting hardware scaling level to " + this._currentScale;
  98058. };
  98059. /**
  98060. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98061. * @param scene defines the current scene where to apply this optimization
  98062. * @param optimizer defines the current optimizer
  98063. * @returns true if everything that can be done was applied
  98064. */
  98065. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  98066. if (this._currentScale === -1) {
  98067. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  98068. if (this._currentScale > this.maximumScale) {
  98069. this._directionOffset = -1;
  98070. }
  98071. }
  98072. this._currentScale += this._directionOffset * this.step;
  98073. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  98074. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  98075. };
  98076. ;
  98077. return HardwareScalingOptimization;
  98078. }(SceneOptimization));
  98079. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  98080. /**
  98081. * Defines an optimization used to remove shadows
  98082. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98083. */
  98084. var ShadowsOptimization = /** @class */ (function (_super) {
  98085. __extends(ShadowsOptimization, _super);
  98086. function ShadowsOptimization() {
  98087. return _super !== null && _super.apply(this, arguments) || this;
  98088. }
  98089. /**
  98090. * Gets a string describing the action executed by the current optimization
  98091. * @return description string
  98092. */
  98093. ShadowsOptimization.prototype.getDescription = function () {
  98094. return "Turning shadows on/off";
  98095. };
  98096. /**
  98097. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98098. * @param scene defines the current scene where to apply this optimization
  98099. * @param optimizer defines the current optimizer
  98100. * @returns true if everything that can be done was applied
  98101. */
  98102. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  98103. scene.shadowsEnabled = optimizer.isInImprovementMode;
  98104. return true;
  98105. };
  98106. ;
  98107. return ShadowsOptimization;
  98108. }(SceneOptimization));
  98109. BABYLON.ShadowsOptimization = ShadowsOptimization;
  98110. /**
  98111. * Defines an optimization used to turn post-processes off
  98112. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98113. */
  98114. var PostProcessesOptimization = /** @class */ (function (_super) {
  98115. __extends(PostProcessesOptimization, _super);
  98116. function PostProcessesOptimization() {
  98117. return _super !== null && _super.apply(this, arguments) || this;
  98118. }
  98119. /**
  98120. * Gets a string describing the action executed by the current optimization
  98121. * @return description string
  98122. */
  98123. PostProcessesOptimization.prototype.getDescription = function () {
  98124. return "Turning post-processes on/off";
  98125. };
  98126. /**
  98127. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98128. * @param scene defines the current scene where to apply this optimization
  98129. * @param optimizer defines the current optimizer
  98130. * @returns true if everything that can be done was applied
  98131. */
  98132. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  98133. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  98134. return true;
  98135. };
  98136. ;
  98137. return PostProcessesOptimization;
  98138. }(SceneOptimization));
  98139. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  98140. /**
  98141. * Defines an optimization used to turn lens flares off
  98142. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98143. */
  98144. var LensFlaresOptimization = /** @class */ (function (_super) {
  98145. __extends(LensFlaresOptimization, _super);
  98146. function LensFlaresOptimization() {
  98147. return _super !== null && _super.apply(this, arguments) || this;
  98148. }
  98149. /**
  98150. * Gets a string describing the action executed by the current optimization
  98151. * @return description string
  98152. */
  98153. LensFlaresOptimization.prototype.getDescription = function () {
  98154. return "Turning lens flares on/off";
  98155. };
  98156. /**
  98157. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98158. * @param scene defines the current scene where to apply this optimization
  98159. * @param optimizer defines the current optimizer
  98160. * @returns true if everything that can be done was applied
  98161. */
  98162. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  98163. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  98164. return true;
  98165. };
  98166. ;
  98167. return LensFlaresOptimization;
  98168. }(SceneOptimization));
  98169. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  98170. /**
  98171. * Defines an optimization based on user defined callback.
  98172. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98173. */
  98174. var CustomOptimization = /** @class */ (function (_super) {
  98175. __extends(CustomOptimization, _super);
  98176. function CustomOptimization() {
  98177. return _super !== null && _super.apply(this, arguments) || this;
  98178. }
  98179. /**
  98180. * Gets a string describing the action executed by the current optimization
  98181. * @returns description string
  98182. */
  98183. CustomOptimization.prototype.getDescription = function () {
  98184. if (this.onGetDescription) {
  98185. return this.onGetDescription();
  98186. }
  98187. return "Running user defined callback";
  98188. };
  98189. /**
  98190. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98191. * @param scene defines the current scene where to apply this optimization
  98192. * @param optimizer defines the current optimizer
  98193. * @returns true if everything that can be done was applied
  98194. */
  98195. CustomOptimization.prototype.apply = function (scene, optimizer) {
  98196. if (this.onApply) {
  98197. return this.onApply(scene, optimizer);
  98198. }
  98199. return true;
  98200. };
  98201. ;
  98202. return CustomOptimization;
  98203. }(SceneOptimization));
  98204. BABYLON.CustomOptimization = CustomOptimization;
  98205. /**
  98206. * Defines an optimization used to turn particles off
  98207. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98208. */
  98209. var ParticlesOptimization = /** @class */ (function (_super) {
  98210. __extends(ParticlesOptimization, _super);
  98211. function ParticlesOptimization() {
  98212. return _super !== null && _super.apply(this, arguments) || this;
  98213. }
  98214. /**
  98215. * Gets a string describing the action executed by the current optimization
  98216. * @return description string
  98217. */
  98218. ParticlesOptimization.prototype.getDescription = function () {
  98219. return "Turning particles on/off";
  98220. };
  98221. /**
  98222. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98223. * @param scene defines the current scene where to apply this optimization
  98224. * @param optimizer defines the current optimizer
  98225. * @returns true if everything that can be done was applied
  98226. */
  98227. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  98228. scene.particlesEnabled = optimizer.isInImprovementMode;
  98229. return true;
  98230. };
  98231. ;
  98232. return ParticlesOptimization;
  98233. }(SceneOptimization));
  98234. BABYLON.ParticlesOptimization = ParticlesOptimization;
  98235. /**
  98236. * Defines an optimization used to turn render targets off
  98237. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98238. */
  98239. var RenderTargetsOptimization = /** @class */ (function (_super) {
  98240. __extends(RenderTargetsOptimization, _super);
  98241. function RenderTargetsOptimization() {
  98242. return _super !== null && _super.apply(this, arguments) || this;
  98243. }
  98244. /**
  98245. * Gets a string describing the action executed by the current optimization
  98246. * @return description string
  98247. */
  98248. RenderTargetsOptimization.prototype.getDescription = function () {
  98249. return "Turning render targets off";
  98250. };
  98251. /**
  98252. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98253. * @param scene defines the current scene where to apply this optimization
  98254. * @param optimizer defines the current optimizer
  98255. * @returns true if everything that can be done was applied
  98256. */
  98257. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  98258. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  98259. return true;
  98260. };
  98261. ;
  98262. return RenderTargetsOptimization;
  98263. }(SceneOptimization));
  98264. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  98265. /**
  98266. * Defines an optimization used to merge meshes with compatible materials
  98267. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98268. */
  98269. var MergeMeshesOptimization = /** @class */ (function (_super) {
  98270. __extends(MergeMeshesOptimization, _super);
  98271. function MergeMeshesOptimization() {
  98272. var _this = _super !== null && _super.apply(this, arguments) || this;
  98273. _this._canBeMerged = function (abstractMesh) {
  98274. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  98275. return false;
  98276. }
  98277. var mesh = abstractMesh;
  98278. if (mesh.isDisposed()) {
  98279. return false;
  98280. }
  98281. if (!mesh.isVisible || !mesh.isEnabled()) {
  98282. return false;
  98283. }
  98284. if (mesh.instances.length > 0) {
  98285. return false;
  98286. }
  98287. if (mesh.skeleton || mesh.hasLODLevels) {
  98288. return false;
  98289. }
  98290. return true;
  98291. };
  98292. return _this;
  98293. }
  98294. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  98295. /**
  98296. * Gets or sets a boolean which defines if optimization octree has to be updated
  98297. */
  98298. get: function () {
  98299. return MergeMeshesOptimization._UpdateSelectionTree;
  98300. },
  98301. /**
  98302. * Gets or sets a boolean which defines if optimization octree has to be updated
  98303. */
  98304. set: function (value) {
  98305. MergeMeshesOptimization._UpdateSelectionTree = value;
  98306. },
  98307. enumerable: true,
  98308. configurable: true
  98309. });
  98310. /**
  98311. * Gets a string describing the action executed by the current optimization
  98312. * @return description string
  98313. */
  98314. MergeMeshesOptimization.prototype.getDescription = function () {
  98315. return "Merging similar meshes together";
  98316. };
  98317. /**
  98318. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98319. * @param scene defines the current scene where to apply this optimization
  98320. * @param optimizer defines the current optimizer
  98321. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  98322. * @returns true if everything that can be done was applied
  98323. */
  98324. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  98325. var globalPool = scene.meshes.slice(0);
  98326. var globalLength = globalPool.length;
  98327. for (var index = 0; index < globalLength; index++) {
  98328. var currentPool = new Array();
  98329. var current = globalPool[index];
  98330. // Checks
  98331. if (!this._canBeMerged(current)) {
  98332. continue;
  98333. }
  98334. currentPool.push(current);
  98335. // Find compatible meshes
  98336. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  98337. var otherMesh = globalPool[subIndex];
  98338. if (!this._canBeMerged(otherMesh)) {
  98339. continue;
  98340. }
  98341. if (otherMesh.material !== current.material) {
  98342. continue;
  98343. }
  98344. if (otherMesh.checkCollisions !== current.checkCollisions) {
  98345. continue;
  98346. }
  98347. currentPool.push(otherMesh);
  98348. globalLength--;
  98349. globalPool.splice(subIndex, 1);
  98350. subIndex--;
  98351. }
  98352. if (currentPool.length < 2) {
  98353. continue;
  98354. }
  98355. // Merge meshes
  98356. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  98357. }
  98358. if (updateSelectionTree != undefined) {
  98359. if (updateSelectionTree) {
  98360. scene.createOrUpdateSelectionOctree();
  98361. }
  98362. }
  98363. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  98364. scene.createOrUpdateSelectionOctree();
  98365. }
  98366. return true;
  98367. };
  98368. ;
  98369. MergeMeshesOptimization._UpdateSelectionTree = false;
  98370. return MergeMeshesOptimization;
  98371. }(SceneOptimization));
  98372. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  98373. /**
  98374. * Defines a list of options used by SceneOptimizer
  98375. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98376. */
  98377. var SceneOptimizerOptions = /** @class */ (function () {
  98378. /**
  98379. * Creates a new list of options used by SceneOptimizer
  98380. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  98381. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  98382. */
  98383. function SceneOptimizerOptions(
  98384. /**
  98385. * Defines the target frame rate to reach (60 by default)
  98386. */
  98387. targetFrameRate,
  98388. /**
  98389. * Defines the interval between two checkes (2000ms by default)
  98390. */
  98391. trackerDuration) {
  98392. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  98393. if (trackerDuration === void 0) { trackerDuration = 2000; }
  98394. this.targetFrameRate = targetFrameRate;
  98395. this.trackerDuration = trackerDuration;
  98396. /**
  98397. * Gets the list of optimizations to apply
  98398. */
  98399. this.optimizations = new Array();
  98400. }
  98401. /**
  98402. * Add a new optimization
  98403. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  98404. * @returns the current SceneOptimizerOptions
  98405. */
  98406. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  98407. this.optimizations.push(optimization);
  98408. return this;
  98409. };
  98410. /**
  98411. * Add a new custom optimization
  98412. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  98413. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  98414. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98415. * @returns the current SceneOptimizerOptions
  98416. */
  98417. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  98418. if (priority === void 0) { priority = 0; }
  98419. var optimization = new CustomOptimization(priority);
  98420. optimization.onApply = onApply;
  98421. optimization.onGetDescription = onGetDescription;
  98422. this.optimizations.push(optimization);
  98423. return this;
  98424. };
  98425. /**
  98426. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  98427. * @param targetFrameRate defines the target frame rate (60 by default)
  98428. * @returns a SceneOptimizerOptions object
  98429. */
  98430. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  98431. var result = new SceneOptimizerOptions(targetFrameRate);
  98432. var priority = 0;
  98433. result.addOptimization(new MergeMeshesOptimization(priority));
  98434. result.addOptimization(new ShadowsOptimization(priority));
  98435. result.addOptimization(new LensFlaresOptimization(priority));
  98436. // Next priority
  98437. priority++;
  98438. result.addOptimization(new PostProcessesOptimization(priority));
  98439. result.addOptimization(new ParticlesOptimization(priority));
  98440. // Next priority
  98441. priority++;
  98442. result.addOptimization(new TextureOptimization(priority, 1024));
  98443. return result;
  98444. };
  98445. /**
  98446. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  98447. * @param targetFrameRate defines the target frame rate (60 by default)
  98448. * @returns a SceneOptimizerOptions object
  98449. */
  98450. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  98451. var result = new SceneOptimizerOptions(targetFrameRate);
  98452. var priority = 0;
  98453. result.addOptimization(new MergeMeshesOptimization(priority));
  98454. result.addOptimization(new ShadowsOptimization(priority));
  98455. result.addOptimization(new LensFlaresOptimization(priority));
  98456. // Next priority
  98457. priority++;
  98458. result.addOptimization(new PostProcessesOptimization(priority));
  98459. result.addOptimization(new ParticlesOptimization(priority));
  98460. // Next priority
  98461. priority++;
  98462. result.addOptimization(new TextureOptimization(priority, 512));
  98463. // Next priority
  98464. priority++;
  98465. result.addOptimization(new RenderTargetsOptimization(priority));
  98466. // Next priority
  98467. priority++;
  98468. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  98469. return result;
  98470. };
  98471. /**
  98472. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  98473. * @param targetFrameRate defines the target frame rate (60 by default)
  98474. * @returns a SceneOptimizerOptions object
  98475. */
  98476. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  98477. var result = new SceneOptimizerOptions(targetFrameRate);
  98478. var priority = 0;
  98479. result.addOptimization(new MergeMeshesOptimization(priority));
  98480. result.addOptimization(new ShadowsOptimization(priority));
  98481. result.addOptimization(new LensFlaresOptimization(priority));
  98482. // Next priority
  98483. priority++;
  98484. result.addOptimization(new PostProcessesOptimization(priority));
  98485. result.addOptimization(new ParticlesOptimization(priority));
  98486. // Next priority
  98487. priority++;
  98488. result.addOptimization(new TextureOptimization(priority, 256));
  98489. // Next priority
  98490. priority++;
  98491. result.addOptimization(new RenderTargetsOptimization(priority));
  98492. // Next priority
  98493. priority++;
  98494. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  98495. return result;
  98496. };
  98497. return SceneOptimizerOptions;
  98498. }());
  98499. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  98500. /**
  98501. * Class used to run optimizations in order to reach a target frame rate
  98502. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98503. */
  98504. var SceneOptimizer = /** @class */ (function () {
  98505. /**
  98506. * Creates a new SceneOptimizer
  98507. * @param scene defines the scene to work on
  98508. * @param options defines the options to use with the SceneOptimizer
  98509. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  98510. * @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)
  98511. */
  98512. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  98513. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  98514. if (improvementMode === void 0) { improvementMode = false; }
  98515. var _this = this;
  98516. this._isRunning = false;
  98517. this._currentPriorityLevel = 0;
  98518. this._targetFrameRate = 60;
  98519. this._trackerDuration = 2000;
  98520. this._currentFrameRate = 0;
  98521. this._improvementMode = false;
  98522. /**
  98523. * Defines an observable called when the optimizer reaches the target frame rate
  98524. */
  98525. this.onSuccessObservable = new BABYLON.Observable();
  98526. /**
  98527. * Defines an observable called when the optimizer enables an optimization
  98528. */
  98529. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  98530. /**
  98531. * Defines an observable called when the optimizer is not able to reach the target frame rate
  98532. */
  98533. this.onFailureObservable = new BABYLON.Observable();
  98534. if (!options) {
  98535. this._options = new SceneOptimizerOptions();
  98536. }
  98537. else {
  98538. this._options = options;
  98539. }
  98540. if (this._options.targetFrameRate) {
  98541. this._targetFrameRate = this._options.targetFrameRate;
  98542. }
  98543. if (this._options.trackerDuration) {
  98544. this._trackerDuration = this._options.trackerDuration;
  98545. }
  98546. if (autoGeneratePriorities) {
  98547. var priority = 0;
  98548. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  98549. var optim = _a[_i];
  98550. optim.priority = priority++;
  98551. }
  98552. }
  98553. this._improvementMode = improvementMode;
  98554. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98555. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  98556. _this._sceneDisposeObserver = null;
  98557. _this.dispose();
  98558. });
  98559. }
  98560. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  98561. /**
  98562. * Gets a boolean indicating if the optimizer is in improvement mode
  98563. */
  98564. get: function () {
  98565. return this._improvementMode;
  98566. },
  98567. enumerable: true,
  98568. configurable: true
  98569. });
  98570. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  98571. /**
  98572. * Gets the current priority level (0 at start)
  98573. */
  98574. get: function () {
  98575. return this._currentPriorityLevel;
  98576. },
  98577. enumerable: true,
  98578. configurable: true
  98579. });
  98580. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  98581. /**
  98582. * Gets the current frame rate checked by the SceneOptimizer
  98583. */
  98584. get: function () {
  98585. return this._currentFrameRate;
  98586. },
  98587. enumerable: true,
  98588. configurable: true
  98589. });
  98590. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  98591. /**
  98592. * Gets or sets the current target frame rate (60 by default)
  98593. */
  98594. get: function () {
  98595. return this._targetFrameRate;
  98596. },
  98597. /**
  98598. * Gets or sets the current target frame rate (60 by default)
  98599. */
  98600. set: function (value) {
  98601. this._targetFrameRate = value;
  98602. },
  98603. enumerable: true,
  98604. configurable: true
  98605. });
  98606. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  98607. /**
  98608. * Gets or sets the current interval between two checks (every 2000ms by default)
  98609. */
  98610. get: function () {
  98611. return this._trackerDuration;
  98612. },
  98613. /**
  98614. * Gets or sets the current interval between two checks (every 2000ms by default)
  98615. */
  98616. set: function (value) {
  98617. this._trackerDuration = value;
  98618. },
  98619. enumerable: true,
  98620. configurable: true
  98621. });
  98622. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  98623. /**
  98624. * Gets the list of active optimizations
  98625. */
  98626. get: function () {
  98627. return this._options.optimizations;
  98628. },
  98629. enumerable: true,
  98630. configurable: true
  98631. });
  98632. /**
  98633. * Stops the current optimizer
  98634. */
  98635. SceneOptimizer.prototype.stop = function () {
  98636. this._isRunning = false;
  98637. };
  98638. /**
  98639. * Reset the optimizer to initial step (current priority level = 0)
  98640. */
  98641. SceneOptimizer.prototype.reset = function () {
  98642. this._currentPriorityLevel = 0;
  98643. };
  98644. /**
  98645. * Start the optimizer. By default it will try to reach a specific framerate
  98646. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  98647. */
  98648. SceneOptimizer.prototype.start = function () {
  98649. var _this = this;
  98650. if (this._isRunning) {
  98651. return;
  98652. }
  98653. this._isRunning = true;
  98654. // Let's wait for the scene to be ready before running our check
  98655. this._scene.executeWhenReady(function () {
  98656. setTimeout(function () {
  98657. _this._checkCurrentState();
  98658. }, _this._trackerDuration);
  98659. });
  98660. };
  98661. SceneOptimizer.prototype._checkCurrentState = function () {
  98662. var _this = this;
  98663. if (!this._isRunning) {
  98664. return;
  98665. }
  98666. var scene = this._scene;
  98667. var options = this._options;
  98668. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  98669. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  98670. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  98671. this._isRunning = false;
  98672. this.onSuccessObservable.notifyObservers(this);
  98673. return;
  98674. }
  98675. // Apply current level of optimizations
  98676. var allDone = true;
  98677. var noOptimizationApplied = true;
  98678. for (var index = 0; index < options.optimizations.length; index++) {
  98679. var optimization = options.optimizations[index];
  98680. if (optimization.priority === this._currentPriorityLevel) {
  98681. noOptimizationApplied = false;
  98682. allDone = allDone && optimization.apply(scene, this);
  98683. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  98684. }
  98685. }
  98686. // If no optimization was applied, this is a failure :(
  98687. if (noOptimizationApplied) {
  98688. this._isRunning = false;
  98689. this.onFailureObservable.notifyObservers(this);
  98690. return;
  98691. }
  98692. // If all optimizations were done, move to next level
  98693. if (allDone) {
  98694. this._currentPriorityLevel++;
  98695. }
  98696. // Let's the system running for a specific amount of time before checking FPS
  98697. scene.executeWhenReady(function () {
  98698. setTimeout(function () {
  98699. _this._checkCurrentState();
  98700. }, _this._trackerDuration);
  98701. });
  98702. };
  98703. /**
  98704. * Release all resources
  98705. */
  98706. SceneOptimizer.prototype.dispose = function () {
  98707. this.stop();
  98708. this.onSuccessObservable.clear();
  98709. this.onFailureObservable.clear();
  98710. this.onNewOptimizationAppliedObservable.clear();
  98711. if (this._sceneDisposeObserver) {
  98712. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  98713. }
  98714. };
  98715. /**
  98716. * Helper function to create a SceneOptimizer with one single line of code
  98717. * @param scene defines the scene to work on
  98718. * @param options defines the options to use with the SceneOptimizer
  98719. * @param onSuccess defines a callback to call on success
  98720. * @param onFailure defines a callback to call on failure
  98721. * @returns the new SceneOptimizer object
  98722. */
  98723. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  98724. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  98725. if (onSuccess) {
  98726. optimizer.onSuccessObservable.add(function () {
  98727. onSuccess();
  98728. });
  98729. }
  98730. if (onFailure) {
  98731. optimizer.onFailureObservable.add(function () {
  98732. onFailure();
  98733. });
  98734. }
  98735. optimizer.start();
  98736. return optimizer;
  98737. };
  98738. return SceneOptimizer;
  98739. }());
  98740. BABYLON.SceneOptimizer = SceneOptimizer;
  98741. })(BABYLON || (BABYLON = {}));
  98742. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  98743. var BABYLON;
  98744. (function (BABYLON) {
  98745. var OutlineRenderer = /** @class */ (function () {
  98746. function OutlineRenderer(scene) {
  98747. this.zOffset = 1;
  98748. this._scene = scene;
  98749. }
  98750. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  98751. var _this = this;
  98752. if (useOverlay === void 0) { useOverlay = false; }
  98753. var scene = this._scene;
  98754. var engine = this._scene.getEngine();
  98755. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  98756. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  98757. return;
  98758. }
  98759. var mesh = subMesh.getRenderingMesh();
  98760. var material = subMesh.getMaterial();
  98761. if (!material || !scene.activeCamera) {
  98762. return;
  98763. }
  98764. engine.enableEffect(this._effect);
  98765. // Logarithmic depth
  98766. if (material.useLogarithmicDepth) {
  98767. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  98768. }
  98769. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  98770. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  98771. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  98772. // Bones
  98773. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  98774. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  98775. }
  98776. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  98777. // Alpha test
  98778. if (material && material.needAlphaTesting()) {
  98779. var alphaTexture = material.getAlphaTestTexture();
  98780. if (alphaTexture) {
  98781. this._effect.setTexture("diffuseSampler", alphaTexture);
  98782. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  98783. }
  98784. }
  98785. engine.setZOffset(-this.zOffset);
  98786. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  98787. engine.setZOffset(0);
  98788. };
  98789. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  98790. var defines = [];
  98791. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  98792. var mesh = subMesh.getMesh();
  98793. var material = subMesh.getMaterial();
  98794. if (material) {
  98795. // Alpha test
  98796. if (material.needAlphaTesting()) {
  98797. defines.push("#define ALPHATEST");
  98798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98799. attribs.push(BABYLON.VertexBuffer.UVKind);
  98800. defines.push("#define UV1");
  98801. }
  98802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  98803. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98804. defines.push("#define UV2");
  98805. }
  98806. }
  98807. //Logarithmic depth
  98808. if (material.useLogarithmicDepth) {
  98809. defines.push("#define LOGARITHMICDEPTH");
  98810. }
  98811. }
  98812. // Bones
  98813. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98814. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98815. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98816. if (mesh.numBoneInfluencers > 4) {
  98817. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98818. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98819. }
  98820. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98821. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  98822. }
  98823. else {
  98824. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98825. }
  98826. // Instances
  98827. if (useInstances) {
  98828. defines.push("#define INSTANCES");
  98829. attribs.push("world0");
  98830. attribs.push("world1");
  98831. attribs.push("world2");
  98832. attribs.push("world3");
  98833. }
  98834. // Get correct effect
  98835. var join = defines.join("\n");
  98836. if (this._cachedDefines !== join) {
  98837. this._cachedDefines = join;
  98838. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  98839. }
  98840. return this._effect.isReady();
  98841. };
  98842. return OutlineRenderer;
  98843. }());
  98844. BABYLON.OutlineRenderer = OutlineRenderer;
  98845. })(BABYLON || (BABYLON = {}));
  98846. //# sourceMappingURL=babylon.outlineRenderer.js.map
  98847. var BABYLON;
  98848. (function (BABYLON) {
  98849. /**
  98850. * FaceAdjacencies Helper class to generate edges
  98851. */
  98852. var FaceAdjacencies = /** @class */ (function () {
  98853. function FaceAdjacencies() {
  98854. this.edges = new Array();
  98855. this.edgesConnectedCount = 0;
  98856. }
  98857. return FaceAdjacencies;
  98858. }());
  98859. /**
  98860. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  98861. */
  98862. var EdgesRenderer = /** @class */ (function () {
  98863. /**
  98864. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  98865. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  98866. * @param source Mesh used to create edges
  98867. * @param epsilon sum of angles in adjacency to check for edge
  98868. * @param checkVerticesInsteadOfIndices
  98869. * @param generateEdgesLines - should generate Lines or only prepare resources.
  98870. */
  98871. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  98872. if (epsilon === void 0) { epsilon = 0.95; }
  98873. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  98874. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  98875. this.edgesWidthScalerForOrthographic = 1000.0;
  98876. this.edgesWidthScalerForPerspective = 50.0;
  98877. this._linesPositions = new Array();
  98878. this._linesNormals = new Array();
  98879. this._linesIndices = new Array();
  98880. this._buffers = {};
  98881. this._checkVerticesInsteadOfIndices = false;
  98882. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  98883. this.isEnabled = true;
  98884. this._source = source;
  98885. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  98886. this._epsilon = epsilon;
  98887. this._prepareRessources();
  98888. if (generateEdgesLines) {
  98889. this._generateEdgesLines();
  98890. }
  98891. }
  98892. EdgesRenderer.prototype._prepareRessources = function () {
  98893. if (this._lineShader) {
  98894. return;
  98895. }
  98896. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  98897. attributes: ["position", "normal"],
  98898. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  98899. });
  98900. this._lineShader.disableDepthWrite = true;
  98901. this._lineShader.backFaceCulling = false;
  98902. };
  98903. /** @hidden */
  98904. EdgesRenderer.prototype._rebuild = function () {
  98905. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  98906. if (buffer) {
  98907. buffer._rebuild();
  98908. }
  98909. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  98910. if (buffer) {
  98911. buffer._rebuild();
  98912. }
  98913. var scene = this._source.getScene();
  98914. var engine = scene.getEngine();
  98915. this._ib = engine.createIndexBuffer(this._linesIndices);
  98916. };
  98917. /**
  98918. * Releases the required resources for the edges renderer
  98919. */
  98920. EdgesRenderer.prototype.dispose = function () {
  98921. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  98922. if (buffer) {
  98923. buffer.dispose();
  98924. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  98925. }
  98926. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  98927. if (buffer) {
  98928. buffer.dispose();
  98929. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  98930. }
  98931. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  98932. this._lineShader.dispose();
  98933. };
  98934. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  98935. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  98936. return 0;
  98937. }
  98938. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  98939. return 1;
  98940. }
  98941. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  98942. return 2;
  98943. }
  98944. return -1;
  98945. };
  98946. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  98947. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  98948. return 0;
  98949. }
  98950. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  98951. return 1;
  98952. }
  98953. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  98954. return 2;
  98955. }
  98956. return -1;
  98957. };
  98958. /**
  98959. * Checks if the pair of p0 and p1 is en edge
  98960. * @param faceIndex
  98961. * @param edge
  98962. * @param faceNormals
  98963. * @param p0
  98964. * @param p1
  98965. * @private
  98966. */
  98967. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  98968. var needToCreateLine;
  98969. if (edge === undefined) {
  98970. needToCreateLine = true;
  98971. }
  98972. else {
  98973. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  98974. needToCreateLine = dotProduct < this._epsilon;
  98975. }
  98976. if (needToCreateLine) {
  98977. var offset = this._linesPositions.length / 3;
  98978. var normal = p0.subtract(p1);
  98979. normal.normalize();
  98980. // Positions
  98981. this._linesPositions.push(p0.x);
  98982. this._linesPositions.push(p0.y);
  98983. this._linesPositions.push(p0.z);
  98984. this._linesPositions.push(p0.x);
  98985. this._linesPositions.push(p0.y);
  98986. this._linesPositions.push(p0.z);
  98987. this._linesPositions.push(p1.x);
  98988. this._linesPositions.push(p1.y);
  98989. this._linesPositions.push(p1.z);
  98990. this._linesPositions.push(p1.x);
  98991. this._linesPositions.push(p1.y);
  98992. this._linesPositions.push(p1.z);
  98993. // Normals
  98994. this._linesNormals.push(p1.x);
  98995. this._linesNormals.push(p1.y);
  98996. this._linesNormals.push(p1.z);
  98997. this._linesNormals.push(-1);
  98998. this._linesNormals.push(p1.x);
  98999. this._linesNormals.push(p1.y);
  99000. this._linesNormals.push(p1.z);
  99001. this._linesNormals.push(1);
  99002. this._linesNormals.push(p0.x);
  99003. this._linesNormals.push(p0.y);
  99004. this._linesNormals.push(p0.z);
  99005. this._linesNormals.push(-1);
  99006. this._linesNormals.push(p0.x);
  99007. this._linesNormals.push(p0.y);
  99008. this._linesNormals.push(p0.z);
  99009. this._linesNormals.push(1);
  99010. // Indices
  99011. this._linesIndices.push(offset);
  99012. this._linesIndices.push(offset + 1);
  99013. this._linesIndices.push(offset + 2);
  99014. this._linesIndices.push(offset);
  99015. this._linesIndices.push(offset + 2);
  99016. this._linesIndices.push(offset + 3);
  99017. }
  99018. };
  99019. /**
  99020. * Generates lines edges from adjacencjes
  99021. * @private
  99022. */
  99023. EdgesRenderer.prototype._generateEdgesLines = function () {
  99024. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99025. var indices = this._source.getIndices();
  99026. if (!indices || !positions) {
  99027. return;
  99028. }
  99029. // First let's find adjacencies
  99030. var adjacencies = new Array();
  99031. var faceNormals = new Array();
  99032. var index;
  99033. var faceAdjacencies;
  99034. // Prepare faces
  99035. for (index = 0; index < indices.length; index += 3) {
  99036. faceAdjacencies = new FaceAdjacencies();
  99037. var p0Index = indices[index];
  99038. var p1Index = indices[index + 1];
  99039. var p2Index = indices[index + 2];
  99040. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  99041. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  99042. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  99043. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  99044. faceNormal.normalize();
  99045. faceNormals.push(faceNormal);
  99046. adjacencies.push(faceAdjacencies);
  99047. }
  99048. // Scan
  99049. for (index = 0; index < adjacencies.length; index++) {
  99050. faceAdjacencies = adjacencies[index];
  99051. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  99052. var otherFaceAdjacencies = adjacencies[otherIndex];
  99053. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  99054. break;
  99055. }
  99056. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  99057. continue;
  99058. }
  99059. var otherP0 = indices[otherIndex * 3];
  99060. var otherP1 = indices[otherIndex * 3 + 1];
  99061. var otherP2 = indices[otherIndex * 3 + 2];
  99062. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  99063. var otherEdgeIndex = 0;
  99064. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  99065. continue;
  99066. }
  99067. switch (edgeIndex) {
  99068. case 0:
  99069. if (this._checkVerticesInsteadOfIndices) {
  99070. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99071. }
  99072. else {
  99073. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  99074. }
  99075. break;
  99076. case 1:
  99077. if (this._checkVerticesInsteadOfIndices) {
  99078. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99079. }
  99080. else {
  99081. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  99082. }
  99083. break;
  99084. case 2:
  99085. if (this._checkVerticesInsteadOfIndices) {
  99086. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99087. }
  99088. else {
  99089. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  99090. }
  99091. break;
  99092. }
  99093. if (otherEdgeIndex === -1) {
  99094. continue;
  99095. }
  99096. faceAdjacencies.edges[edgeIndex] = otherIndex;
  99097. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  99098. faceAdjacencies.edgesConnectedCount++;
  99099. otherFaceAdjacencies.edgesConnectedCount++;
  99100. if (faceAdjacencies.edgesConnectedCount === 3) {
  99101. break;
  99102. }
  99103. }
  99104. }
  99105. }
  99106. // Create lines
  99107. for (index = 0; index < adjacencies.length; index++) {
  99108. // 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
  99109. var current = adjacencies[index];
  99110. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99111. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  99112. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  99113. }
  99114. // Merge into a single mesh
  99115. var engine = this._source.getScene().getEngine();
  99116. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99117. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99118. this._ib = engine.createIndexBuffer(this._linesIndices);
  99119. this._indicesCount = this._linesIndices.length;
  99120. };
  99121. EdgesRenderer.prototype.render = function () {
  99122. var scene = this._source.getScene();
  99123. if (!this._lineShader.isReady() || !scene.activeCamera) {
  99124. return;
  99125. }
  99126. var engine = scene.getEngine();
  99127. this._lineShader._preBind();
  99128. if (this._source.edgesColor.a !== 1) {
  99129. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  99130. }
  99131. else {
  99132. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99133. }
  99134. // VBOs
  99135. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  99136. scene.resetCachedMaterial();
  99137. this._lineShader.setColor4("color", this._source.edgesColor);
  99138. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  99139. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  99140. }
  99141. else {
  99142. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  99143. }
  99144. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  99145. this._lineShader.bind(this._source.getWorldMatrix());
  99146. // Draw order
  99147. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  99148. this._lineShader.unbind();
  99149. };
  99150. return EdgesRenderer;
  99151. }());
  99152. BABYLON.EdgesRenderer = EdgesRenderer;
  99153. })(BABYLON || (BABYLON = {}));
  99154. //# sourceMappingURL=babylon.edgesRenderer.js.map
  99155. var BABYLON;
  99156. (function (BABYLON) {
  99157. /**
  99158. * FaceAdjacencies Helper class to generate edges
  99159. */
  99160. var FaceAdjacencies = /** @class */ (function () {
  99161. function FaceAdjacencies() {
  99162. this.edges = new Array();
  99163. this.edgesConnectedCount = 0;
  99164. }
  99165. return FaceAdjacencies;
  99166. }());
  99167. /**
  99168. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  99169. */
  99170. var LineEdgesRenderer = /** @class */ (function (_super) {
  99171. __extends(LineEdgesRenderer, _super);
  99172. /**
  99173. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  99174. * @param source LineMesh used to generate edges
  99175. * @param epsilon not important (specified angle for edge detection)
  99176. * @param checkVerticesInsteadOfIndices not important for LineMesh
  99177. */
  99178. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  99179. if (epsilon === void 0) { epsilon = 0.95; }
  99180. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99181. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  99182. _this._generateEdgesLines();
  99183. return _this;
  99184. }
  99185. /**
  99186. * Always create the edge since its a line so only important things are p0 and p1
  99187. * @param faceIndex not important for LineMesh
  99188. * @param edge not important for LineMesh
  99189. * @param faceNormals not important for LineMesh
  99190. * @param p0 beginnig of line
  99191. * @param p1 end of line
  99192. */
  99193. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99194. var offset = this._linesPositions.length / 3;
  99195. var normal = p0.subtract(p1);
  99196. normal.normalize();
  99197. // Positions
  99198. this._linesPositions.push(p0.x);
  99199. this._linesPositions.push(p0.y);
  99200. this._linesPositions.push(p0.z);
  99201. this._linesPositions.push(p0.x);
  99202. this._linesPositions.push(p0.y);
  99203. this._linesPositions.push(p0.z);
  99204. this._linesPositions.push(p1.x);
  99205. this._linesPositions.push(p1.y);
  99206. this._linesPositions.push(p1.z);
  99207. this._linesPositions.push(p1.x);
  99208. this._linesPositions.push(p1.y);
  99209. this._linesPositions.push(p1.z);
  99210. // Normals
  99211. this._linesNormals.push(p1.x);
  99212. this._linesNormals.push(p1.y);
  99213. this._linesNormals.push(p1.z);
  99214. this._linesNormals.push(-1);
  99215. this._linesNormals.push(p1.x);
  99216. this._linesNormals.push(p1.y);
  99217. this._linesNormals.push(p1.z);
  99218. this._linesNormals.push(1);
  99219. this._linesNormals.push(p0.x);
  99220. this._linesNormals.push(p0.y);
  99221. this._linesNormals.push(p0.z);
  99222. this._linesNormals.push(-1);
  99223. this._linesNormals.push(p0.x);
  99224. this._linesNormals.push(p0.y);
  99225. this._linesNormals.push(p0.z);
  99226. this._linesNormals.push(1);
  99227. // Indices
  99228. this._linesIndices.push(offset);
  99229. this._linesIndices.push(offset + 1);
  99230. this._linesIndices.push(offset + 2);
  99231. this._linesIndices.push(offset);
  99232. this._linesIndices.push(offset + 2);
  99233. this._linesIndices.push(offset + 3);
  99234. };
  99235. /**
  99236. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  99237. */
  99238. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  99239. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99240. var indices = this._source.getIndices();
  99241. if (!indices || !positions) {
  99242. return;
  99243. }
  99244. // First let's find adjacencies
  99245. var adjacencies = new Array();
  99246. var faceNormals = new Array();
  99247. var index;
  99248. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  99249. var currentAdjecancy = new FaceAdjacencies();
  99250. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  99251. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  99252. adjacencies.push(currentAdjecancy);
  99253. }
  99254. // Create lines
  99255. for (index = 0; index < adjacencies.length; index++) {
  99256. // 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
  99257. var current = adjacencies[index];
  99258. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99259. }
  99260. // Merge into a single mesh
  99261. var engine = this._source.getScene().getEngine();
  99262. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99263. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99264. this._ib = engine.createIndexBuffer(this._linesIndices);
  99265. this._indicesCount = this._linesIndices.length;
  99266. };
  99267. return LineEdgesRenderer;
  99268. }(BABYLON.EdgesRenderer));
  99269. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  99270. })(BABYLON || (BABYLON = {}));
  99271. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  99272. var BABYLON;
  99273. (function (BABYLON) {
  99274. // Adds the parser to the scene parsers.
  99275. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  99276. if (parsedData.effectLayers) {
  99277. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  99278. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  99279. container.effectLayers.push(effectLayer);
  99280. }
  99281. }
  99282. });
  99283. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  99284. var index = this.effectLayers.indexOf(toRemove);
  99285. if (index !== -1) {
  99286. this.effectLayers.splice(index, 1);
  99287. }
  99288. return index;
  99289. };
  99290. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  99291. this.effectLayers.push(newEffectLayer);
  99292. };
  99293. /**
  99294. * Defines the layer scene component responsible to manage any effect layers
  99295. * in a given scene.
  99296. */
  99297. var EffectLayerSceneComponent = /** @class */ (function () {
  99298. /**
  99299. * Creates a new instance of the component for the given scene
  99300. * @param scene Defines the scene to register the component in
  99301. */
  99302. function EffectLayerSceneComponent(scene) {
  99303. /**
  99304. * The component name helpfull to identify the component in the list of scene components.
  99305. */
  99306. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  99307. this._renderEffects = false;
  99308. this._needStencil = false;
  99309. this._previousStencilState = false;
  99310. this.scene = scene;
  99311. this._engine = scene.getEngine();
  99312. scene.effectLayers = new Array();
  99313. }
  99314. /**
  99315. * Registers the component in a given scene
  99316. */
  99317. EffectLayerSceneComponent.prototype.register = function () {
  99318. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  99319. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  99320. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  99321. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  99322. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  99323. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  99324. };
  99325. /**
  99326. * Rebuilds the elements related to this component in case of
  99327. * context lost for instance.
  99328. */
  99329. EffectLayerSceneComponent.prototype.rebuild = function () {
  99330. var layers = this.scene.effectLayers;
  99331. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99332. var effectLayer = layers_1[_i];
  99333. effectLayer._rebuild();
  99334. }
  99335. };
  99336. /**
  99337. * Serializes the component data to the specified json object
  99338. * @param serializationObject The object to serialize to
  99339. */
  99340. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  99341. // Effect layers
  99342. serializationObject.effectLayers = [];
  99343. var layers = this.scene.effectLayers;
  99344. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99345. var effectLayer = layers_2[_i];
  99346. if (effectLayer.serialize) {
  99347. serializationObject.effectLayers.push(effectLayer.serialize());
  99348. }
  99349. }
  99350. };
  99351. /**
  99352. * Adds all the element from the container to the scene
  99353. * @param container the container holding the elements
  99354. */
  99355. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  99356. var _this = this;
  99357. if (!container.effectLayers) {
  99358. return;
  99359. }
  99360. container.effectLayers.forEach(function (o) {
  99361. _this.scene.addEffectLayer(o);
  99362. });
  99363. };
  99364. /**
  99365. * Removes all the elements in the container from the scene
  99366. * @param container contains the elements to remove
  99367. */
  99368. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  99369. var _this = this;
  99370. if (!container.effectLayers) {
  99371. return;
  99372. }
  99373. container.effectLayers.forEach(function (o) {
  99374. _this.scene.removeEffectLayer(o);
  99375. });
  99376. };
  99377. /**
  99378. * Disposes the component and the associated ressources.
  99379. */
  99380. EffectLayerSceneComponent.prototype.dispose = function () {
  99381. var layers = this.scene.effectLayers;
  99382. while (layers.length) {
  99383. layers[0].dispose();
  99384. }
  99385. };
  99386. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  99387. var layers = this.scene.effectLayers;
  99388. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  99389. var layer = layers_3[_i];
  99390. if (!layer.hasMesh(mesh)) {
  99391. continue;
  99392. }
  99393. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  99394. var subMesh = _b[_a];
  99395. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  99396. return false;
  99397. }
  99398. }
  99399. }
  99400. return true;
  99401. };
  99402. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  99403. this._renderEffects = false;
  99404. this._needStencil = false;
  99405. var layers = this.scene.effectLayers;
  99406. if (layers && layers.length > 0) {
  99407. this._previousStencilState = this._engine.getStencilBuffer();
  99408. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  99409. var effectLayer = layers_4[_i];
  99410. if (effectLayer.shouldRender() &&
  99411. (!effectLayer.camera ||
  99412. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  99413. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  99414. this._renderEffects = true;
  99415. this._needStencil = this._needStencil || effectLayer.needStencil();
  99416. var renderTarget = effectLayer._mainTexture;
  99417. if (renderTarget._shouldRender()) {
  99418. this.scene.incrementRenderId();
  99419. renderTarget.render(false, false);
  99420. }
  99421. }
  99422. }
  99423. this.scene.incrementRenderId();
  99424. }
  99425. };
  99426. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  99427. // Activate effect Layer stencil
  99428. if (this._needStencil) {
  99429. this._engine.setStencilBuffer(true);
  99430. }
  99431. };
  99432. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  99433. // Restore effect Layer stencil
  99434. if (this._needStencil) {
  99435. this._engine.setStencilBuffer(this._previousStencilState);
  99436. }
  99437. };
  99438. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  99439. if (this._renderEffects) {
  99440. this._engine.setDepthBuffer(false);
  99441. var layers = this.scene.effectLayers;
  99442. for (var i = 0; i < layers.length; i++) {
  99443. var effectLayer = layers[i];
  99444. if (effectLayer.renderingGroupId === renderingGroupId) {
  99445. if (effectLayer.shouldRender()) {
  99446. effectLayer.render();
  99447. }
  99448. }
  99449. }
  99450. this._engine.setDepthBuffer(true);
  99451. }
  99452. };
  99453. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  99454. if (this._renderEffects) {
  99455. this._draw(-1);
  99456. }
  99457. };
  99458. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  99459. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  99460. this._draw(index);
  99461. }
  99462. };
  99463. return EffectLayerSceneComponent;
  99464. }());
  99465. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  99466. })(BABYLON || (BABYLON = {}));
  99467. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  99468. var __assign = (this && this.__assign) || function () {
  99469. __assign = Object.assign || function(t) {
  99470. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99471. s = arguments[i];
  99472. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99473. t[p] = s[p];
  99474. }
  99475. return t;
  99476. };
  99477. return __assign.apply(this, arguments);
  99478. };
  99479. var BABYLON;
  99480. (function (BABYLON) {
  99481. /**
  99482. * The effect layer Helps adding post process effect blended with the main pass.
  99483. *
  99484. * This can be for instance use to generate glow or higlight effects on the scene.
  99485. *
  99486. * The effect layer class can not be used directly and is intented to inherited from to be
  99487. * customized per effects.
  99488. */
  99489. var EffectLayer = /** @class */ (function () {
  99490. /**
  99491. * Instantiates a new effect Layer and references it in the scene.
  99492. * @param name The name of the layer
  99493. * @param scene The scene to use the layer in
  99494. */
  99495. function EffectLayer(
  99496. /** The Friendly of the effect in the scene */
  99497. name, scene) {
  99498. this._vertexBuffers = {};
  99499. this._maxSize = 0;
  99500. this._mainTextureDesiredSize = { width: 0, height: 0 };
  99501. this._shouldRender = true;
  99502. this._postProcesses = [];
  99503. this._textures = [];
  99504. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  99505. /**
  99506. * The clear color of the texture used to generate the glow map.
  99507. */
  99508. this.neutralColor = new BABYLON.Color4();
  99509. /**
  99510. * Specifies wether the highlight layer is enabled or not.
  99511. */
  99512. this.isEnabled = true;
  99513. /**
  99514. * An event triggered when the effect layer has been disposed.
  99515. */
  99516. this.onDisposeObservable = new BABYLON.Observable();
  99517. /**
  99518. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  99519. */
  99520. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  99521. /**
  99522. * An event triggered when the generated texture is being merged in the scene.
  99523. */
  99524. this.onBeforeComposeObservable = new BABYLON.Observable();
  99525. /**
  99526. * An event triggered when the generated texture has been merged in the scene.
  99527. */
  99528. this.onAfterComposeObservable = new BABYLON.Observable();
  99529. /**
  99530. * An event triggered when the efffect layer changes its size.
  99531. */
  99532. this.onSizeChangedObservable = new BABYLON.Observable();
  99533. this.name = name;
  99534. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99535. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  99536. if (!component) {
  99537. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  99538. this._scene._addComponent(component);
  99539. }
  99540. this._engine = this._scene.getEngine();
  99541. this._maxSize = this._engine.getCaps().maxTextureSize;
  99542. this._scene.effectLayers.push(this);
  99543. // Generate Buffers
  99544. this._generateIndexBuffer();
  99545. this._genrateVertexBuffer();
  99546. }
  99547. Object.defineProperty(EffectLayer.prototype, "camera", {
  99548. /**
  99549. * Gets the camera attached to the layer.
  99550. */
  99551. get: function () {
  99552. return this._effectLayerOptions.camera;
  99553. },
  99554. enumerable: true,
  99555. configurable: true
  99556. });
  99557. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  99558. /**
  99559. * Gets the rendering group id the layer should render in.
  99560. */
  99561. get: function () {
  99562. return this._effectLayerOptions.renderingGroupId;
  99563. },
  99564. enumerable: true,
  99565. configurable: true
  99566. });
  99567. /**
  99568. * Initializes the effect layer with the required options.
  99569. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  99570. */
  99571. EffectLayer.prototype._init = function (options) {
  99572. // Adapt options
  99573. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  99574. this._setMainTextureSize();
  99575. this._createMainTexture();
  99576. this._createTextureAndPostProcesses();
  99577. this._mergeEffect = this._createMergeEffect();
  99578. };
  99579. /**
  99580. * Generates the index buffer of the full screen quad blending to the main canvas.
  99581. */
  99582. EffectLayer.prototype._generateIndexBuffer = function () {
  99583. // Indices
  99584. var indices = [];
  99585. indices.push(0);
  99586. indices.push(1);
  99587. indices.push(2);
  99588. indices.push(0);
  99589. indices.push(2);
  99590. indices.push(3);
  99591. this._indexBuffer = this._engine.createIndexBuffer(indices);
  99592. };
  99593. /**
  99594. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  99595. */
  99596. EffectLayer.prototype._genrateVertexBuffer = function () {
  99597. // VBO
  99598. var vertices = [];
  99599. vertices.push(1, 1);
  99600. vertices.push(-1, 1);
  99601. vertices.push(-1, -1);
  99602. vertices.push(1, -1);
  99603. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99604. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99605. };
  99606. /**
  99607. * Sets the main texture desired size which is the closest power of two
  99608. * of the engine canvas size.
  99609. */
  99610. EffectLayer.prototype._setMainTextureSize = function () {
  99611. if (this._effectLayerOptions.mainTextureFixedSize) {
  99612. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  99613. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  99614. }
  99615. else {
  99616. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  99617. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  99618. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  99619. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  99620. }
  99621. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  99622. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  99623. };
  99624. /**
  99625. * Creates the main texture for the effect layer.
  99626. */
  99627. EffectLayer.prototype._createMainTexture = function () {
  99628. var _this = this;
  99629. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  99630. width: this._mainTextureDesiredSize.width,
  99631. height: this._mainTextureDesiredSize.height
  99632. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99633. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  99634. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99635. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99636. this._mainTexture.anisotropicFilteringLevel = 1;
  99637. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99638. this._mainTexture.renderParticles = false;
  99639. this._mainTexture.renderList = null;
  99640. this._mainTexture.ignoreCameraViewport = true;
  99641. // Custom render function
  99642. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  99643. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  99644. var index;
  99645. var engine = _this._scene.getEngine();
  99646. if (depthOnlySubMeshes.length) {
  99647. engine.setColorWrite(false);
  99648. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  99649. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  99650. }
  99651. engine.setColorWrite(true);
  99652. }
  99653. for (index = 0; index < opaqueSubMeshes.length; index++) {
  99654. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  99655. }
  99656. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  99657. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  99658. }
  99659. for (index = 0; index < transparentSubMeshes.length; index++) {
  99660. _this._renderSubMesh(transparentSubMeshes.data[index]);
  99661. }
  99662. };
  99663. this._mainTexture.onClearObservable.add(function (engine) {
  99664. engine.clear(_this.neutralColor, true, true, true);
  99665. });
  99666. };
  99667. /**
  99668. * Checks for the readiness of the element composing the layer.
  99669. * @param subMesh the mesh to check for
  99670. * @param useInstances specify wether or not to use instances to render the mesh
  99671. * @param emissiveTexture the associated emissive texture used to generate the glow
  99672. * @return true if ready otherwise, false
  99673. */
  99674. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  99675. var material = subMesh.getMaterial();
  99676. if (!material) {
  99677. return false;
  99678. }
  99679. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  99680. return false;
  99681. }
  99682. var defines = [];
  99683. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99684. var mesh = subMesh.getMesh();
  99685. var uv1 = false;
  99686. var uv2 = false;
  99687. // Alpha test
  99688. if (material && material.needAlphaTesting()) {
  99689. var alphaTexture = material.getAlphaTestTexture();
  99690. if (alphaTexture) {
  99691. defines.push("#define ALPHATEST");
  99692. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  99693. alphaTexture.coordinatesIndex === 1) {
  99694. defines.push("#define DIFFUSEUV2");
  99695. uv2 = true;
  99696. }
  99697. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99698. defines.push("#define DIFFUSEUV1");
  99699. uv1 = true;
  99700. }
  99701. }
  99702. }
  99703. // Emissive
  99704. if (emissiveTexture) {
  99705. defines.push("#define EMISSIVE");
  99706. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  99707. emissiveTexture.coordinatesIndex === 1) {
  99708. defines.push("#define EMISSIVEUV2");
  99709. uv2 = true;
  99710. }
  99711. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99712. defines.push("#define EMISSIVEUV1");
  99713. uv1 = true;
  99714. }
  99715. }
  99716. if (uv1) {
  99717. attribs.push(BABYLON.VertexBuffer.UVKind);
  99718. defines.push("#define UV1");
  99719. }
  99720. if (uv2) {
  99721. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99722. defines.push("#define UV2");
  99723. }
  99724. // Bones
  99725. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99726. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99727. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99728. if (mesh.numBoneInfluencers > 4) {
  99729. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99730. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99731. }
  99732. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99733. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  99734. }
  99735. else {
  99736. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99737. }
  99738. // Morph targets
  99739. var manager = mesh.morphTargetManager;
  99740. var morphInfluencers = 0;
  99741. if (manager) {
  99742. if (manager.numInfluencers > 0) {
  99743. defines.push("#define MORPHTARGETS");
  99744. morphInfluencers = manager.numInfluencers;
  99745. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  99746. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  99747. }
  99748. }
  99749. // Instances
  99750. if (useInstances) {
  99751. defines.push("#define INSTANCES");
  99752. attribs.push("world0");
  99753. attribs.push("world1");
  99754. attribs.push("world2");
  99755. attribs.push("world3");
  99756. }
  99757. // Get correct effect
  99758. var join = defines.join("\n");
  99759. if (this._cachedDefines !== join) {
  99760. this._cachedDefines = join;
  99761. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  99762. }
  99763. return this._effectLayerMapGenerationEffect.isReady();
  99764. };
  99765. /**
  99766. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  99767. */
  99768. EffectLayer.prototype.render = function () {
  99769. var currentEffect = this._mergeEffect;
  99770. // Check
  99771. if (!currentEffect.isReady())
  99772. return;
  99773. for (var i = 0; i < this._postProcesses.length; i++) {
  99774. if (!this._postProcesses[i].isReady()) {
  99775. return;
  99776. }
  99777. }
  99778. var engine = this._scene.getEngine();
  99779. this.onBeforeComposeObservable.notifyObservers(this);
  99780. // Render
  99781. engine.enableEffect(currentEffect);
  99782. engine.setState(false);
  99783. // VBOs
  99784. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99785. // Cache
  99786. var previousAlphaMode = engine.getAlphaMode();
  99787. // Go Blend.
  99788. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  99789. // Blends the map on the main canvas.
  99790. this._internalRender(currentEffect);
  99791. // Restore Alpha
  99792. engine.setAlphaMode(previousAlphaMode);
  99793. this.onAfterComposeObservable.notifyObservers(this);
  99794. // Handle size changes.
  99795. var size = this._mainTexture.getSize();
  99796. this._setMainTextureSize();
  99797. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  99798. // Recreate RTT and post processes on size change.
  99799. this.onSizeChangedObservable.notifyObservers(this);
  99800. this._disposeTextureAndPostProcesses();
  99801. this._createMainTexture();
  99802. this._createTextureAndPostProcesses();
  99803. }
  99804. };
  99805. /**
  99806. * Determine if a given mesh will be used in the current effect.
  99807. * @param mesh mesh to test
  99808. * @returns true if the mesh will be used
  99809. */
  99810. EffectLayer.prototype.hasMesh = function (mesh) {
  99811. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  99812. return true;
  99813. }
  99814. return false;
  99815. };
  99816. /**
  99817. * Returns true if the layer contains information to display, otherwise false.
  99818. * @returns true if the glow layer should be rendered
  99819. */
  99820. EffectLayer.prototype.shouldRender = function () {
  99821. return this.isEnabled && this._shouldRender;
  99822. };
  99823. /**
  99824. * Returns true if the mesh should render, otherwise false.
  99825. * @param mesh The mesh to render
  99826. * @returns true if it should render otherwise false
  99827. */
  99828. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  99829. return true;
  99830. };
  99831. /**
  99832. * Returns true if the mesh should render, otherwise false.
  99833. * @param mesh The mesh to render
  99834. * @returns true if it should render otherwise false
  99835. */
  99836. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  99837. return true;
  99838. };
  99839. /**
  99840. * Renders the submesh passed in parameter to the generation map.
  99841. */
  99842. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  99843. var _this = this;
  99844. if (!this.shouldRender()) {
  99845. return;
  99846. }
  99847. var material = subMesh.getMaterial();
  99848. var mesh = subMesh.getRenderingMesh();
  99849. var scene = this._scene;
  99850. var engine = scene.getEngine();
  99851. if (!material) {
  99852. return;
  99853. }
  99854. // Do not block in blend mode.
  99855. if (material.needAlphaBlendingForMesh(mesh)) {
  99856. return;
  99857. }
  99858. // Culling
  99859. engine.setState(material.backFaceCulling);
  99860. // Managing instances
  99861. var batch = mesh._getInstancesRenderList(subMesh._id);
  99862. if (batch.mustReturn) {
  99863. return;
  99864. }
  99865. // Early Exit per mesh
  99866. if (!this._shouldRenderMesh(mesh)) {
  99867. return;
  99868. }
  99869. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99870. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  99871. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  99872. engine.enableEffect(this._effectLayerMapGenerationEffect);
  99873. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  99874. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  99875. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  99876. // Alpha test
  99877. if (material && material.needAlphaTesting()) {
  99878. var alphaTexture = material.getAlphaTestTexture();
  99879. if (alphaTexture) {
  99880. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  99881. var textureMatrix = alphaTexture.getTextureMatrix();
  99882. if (textureMatrix) {
  99883. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  99884. }
  99885. }
  99886. }
  99887. // Glow emissive only
  99888. if (this._emissiveTextureAndColor.texture) {
  99889. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  99890. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  99891. }
  99892. // Bones
  99893. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99894. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99895. }
  99896. // Morph targets
  99897. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  99898. // Draw
  99899. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  99900. }
  99901. else {
  99902. // Need to reset refresh rate of the main map
  99903. this._mainTexture.resetRefreshCounter();
  99904. }
  99905. };
  99906. /**
  99907. * Rebuild the required buffers.
  99908. * @hidden Internal use only.
  99909. */
  99910. EffectLayer.prototype._rebuild = function () {
  99911. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99912. if (vb) {
  99913. vb._rebuild();
  99914. }
  99915. this._generateIndexBuffer();
  99916. };
  99917. /**
  99918. * Dispose only the render target textures and post process.
  99919. */
  99920. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  99921. this._mainTexture.dispose();
  99922. for (var i = 0; i < this._postProcesses.length; i++) {
  99923. if (this._postProcesses[i]) {
  99924. this._postProcesses[i].dispose();
  99925. }
  99926. }
  99927. this._postProcesses = [];
  99928. for (var i = 0; i < this._textures.length; i++) {
  99929. if (this._textures[i]) {
  99930. this._textures[i].dispose();
  99931. }
  99932. }
  99933. this._textures = [];
  99934. };
  99935. /**
  99936. * Dispose the highlight layer and free resources.
  99937. */
  99938. EffectLayer.prototype.dispose = function () {
  99939. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99940. if (vertexBuffer) {
  99941. vertexBuffer.dispose();
  99942. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99943. }
  99944. if (this._indexBuffer) {
  99945. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99946. this._indexBuffer = null;
  99947. }
  99948. // Clean textures and post processes
  99949. this._disposeTextureAndPostProcesses();
  99950. // Remove from scene
  99951. var index = this._scene.effectLayers.indexOf(this, 0);
  99952. if (index > -1) {
  99953. this._scene.effectLayers.splice(index, 1);
  99954. }
  99955. // Callback
  99956. this.onDisposeObservable.notifyObservers(this);
  99957. this.onDisposeObservable.clear();
  99958. this.onBeforeRenderMainTextureObservable.clear();
  99959. this.onBeforeComposeObservable.clear();
  99960. this.onAfterComposeObservable.clear();
  99961. this.onSizeChangedObservable.clear();
  99962. };
  99963. /**
  99964. * Gets the class name of the effect layer
  99965. * @returns the string with the class name of the effect layer
  99966. */
  99967. EffectLayer.prototype.getClassName = function () {
  99968. return "EffectLayer";
  99969. };
  99970. /**
  99971. * Creates an effect layer from parsed effect layer data
  99972. * @param parsedEffectLayer defines effect layer data
  99973. * @param scene defines the current scene
  99974. * @param rootUrl defines the root URL containing the effect layer information
  99975. * @returns a parsed effect Layer
  99976. */
  99977. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  99978. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  99979. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  99980. };
  99981. __decorate([
  99982. BABYLON.serialize()
  99983. ], EffectLayer.prototype, "name", void 0);
  99984. __decorate([
  99985. BABYLON.serializeAsColor4()
  99986. ], EffectLayer.prototype, "neutralColor", void 0);
  99987. __decorate([
  99988. BABYLON.serialize()
  99989. ], EffectLayer.prototype, "isEnabled", void 0);
  99990. __decorate([
  99991. BABYLON.serializeAsCameraReference()
  99992. ], EffectLayer.prototype, "camera", null);
  99993. __decorate([
  99994. BABYLON.serialize()
  99995. ], EffectLayer.prototype, "renderingGroupId", null);
  99996. return EffectLayer;
  99997. }());
  99998. BABYLON.EffectLayer = EffectLayer;
  99999. })(BABYLON || (BABYLON = {}));
  100000. //# sourceMappingURL=babylon.effectLayer.js.map
  100001. var BABYLON;
  100002. (function (BABYLON) {
  100003. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  100004. for (var index = 0; index < this.effectLayers.length; index++) {
  100005. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  100006. return this.effectLayers[index];
  100007. }
  100008. }
  100009. return null;
  100010. };
  100011. /**
  100012. * Special Glow Blur post process only blurring the alpha channel
  100013. * It enforces keeping the most luminous color in the color channel.
  100014. */
  100015. var GlowBlurPostProcess = /** @class */ (function (_super) {
  100016. __extends(GlowBlurPostProcess, _super);
  100017. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  100018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  100019. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  100020. _this.direction = direction;
  100021. _this.kernel = kernel;
  100022. _this.onApplyObservable.add(function (effect) {
  100023. effect.setFloat2("screenSize", _this.width, _this.height);
  100024. effect.setVector2("direction", _this.direction);
  100025. effect.setFloat("blurWidth", _this.kernel);
  100026. });
  100027. return _this;
  100028. }
  100029. return GlowBlurPostProcess;
  100030. }(BABYLON.PostProcess));
  100031. /**
  100032. * The highlight layer Helps adding a glow effect around a mesh.
  100033. *
  100034. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100035. * glowy meshes to your scene.
  100036. *
  100037. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  100038. */
  100039. var HighlightLayer = /** @class */ (function (_super) {
  100040. __extends(HighlightLayer, _super);
  100041. /**
  100042. * Instantiates a new highlight Layer and references it to the scene..
  100043. * @param name The name of the layer
  100044. * @param scene The scene to use the layer in
  100045. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  100046. */
  100047. function HighlightLayer(name, scene, options) {
  100048. var _this = _super.call(this, name, scene) || this;
  100049. _this.name = name;
  100050. /**
  100051. * Specifies whether or not the inner glow is ACTIVE in the layer.
  100052. */
  100053. _this.innerGlow = true;
  100054. /**
  100055. * Specifies whether or not the outer glow is ACTIVE in the layer.
  100056. */
  100057. _this.outerGlow = true;
  100058. /**
  100059. * An event triggered when the highlight layer is being blurred.
  100060. */
  100061. _this.onBeforeBlurObservable = new BABYLON.Observable();
  100062. /**
  100063. * An event triggered when the highlight layer has been blurred.
  100064. */
  100065. _this.onAfterBlurObservable = new BABYLON.Observable();
  100066. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  100067. _this._meshes = {};
  100068. _this._excludedMeshes = {};
  100069. _this.neutralColor = HighlightLayer.NeutralColor;
  100070. // Warn on stencil
  100071. if (!_this._engine.isStencilEnable) {
  100072. 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 }");
  100073. }
  100074. // Adapt options
  100075. _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);
  100076. // Initialize the layer
  100077. _this._init({
  100078. alphaBlendingMode: _this._options.alphaBlendingMode,
  100079. camera: _this._options.camera,
  100080. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100081. mainTextureRatio: _this._options.mainTextureRatio,
  100082. renderingGroupId: _this._options.renderingGroupId
  100083. });
  100084. // Do not render as long as no meshes have been added
  100085. _this._shouldRender = false;
  100086. return _this;
  100087. }
  100088. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  100089. /**
  100090. * Gets the horizontal size of the blur.
  100091. */
  100092. get: function () {
  100093. return this._horizontalBlurPostprocess.kernel;
  100094. },
  100095. /**
  100096. * Specifies the horizontal size of the blur.
  100097. */
  100098. set: function (value) {
  100099. this._horizontalBlurPostprocess.kernel = value;
  100100. },
  100101. enumerable: true,
  100102. configurable: true
  100103. });
  100104. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  100105. /**
  100106. * Gets the vertical size of the blur.
  100107. */
  100108. get: function () {
  100109. return this._verticalBlurPostprocess.kernel;
  100110. },
  100111. /**
  100112. * Specifies the vertical size of the blur.
  100113. */
  100114. set: function (value) {
  100115. this._verticalBlurPostprocess.kernel = value;
  100116. },
  100117. enumerable: true,
  100118. configurable: true
  100119. });
  100120. /**
  100121. * Get the effect name of the layer.
  100122. * @return The effect name
  100123. */
  100124. HighlightLayer.prototype.getEffectName = function () {
  100125. return HighlightLayer.EffectName;
  100126. };
  100127. /**
  100128. * Create the merge effect. This is the shader use to blit the information back
  100129. * to the main canvas at the end of the scene rendering.
  100130. */
  100131. HighlightLayer.prototype._createMergeEffect = function () {
  100132. // Effect
  100133. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  100134. };
  100135. /**
  100136. * Creates the render target textures and post processes used in the highlight layer.
  100137. */
  100138. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  100139. var _this = this;
  100140. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  100141. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  100142. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100143. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100144. var textureType = 0;
  100145. if (this._engine.getCaps().textureHalfFloatRender) {
  100146. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100147. }
  100148. else {
  100149. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100150. }
  100151. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  100152. width: blurTextureWidth,
  100153. height: blurTextureHeight
  100154. }, this._scene, false, true, textureType);
  100155. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100156. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100157. this._blurTexture.anisotropicFilteringLevel = 16;
  100158. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  100159. this._blurTexture.renderParticles = false;
  100160. this._blurTexture.ignoreCameraViewport = true;
  100161. this._textures = [this._blurTexture];
  100162. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  100163. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100164. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  100165. effect.setTexture("textureSampler", _this._mainTexture);
  100166. });
  100167. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100168. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100169. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100170. });
  100171. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100172. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  100173. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100174. });
  100175. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100176. }
  100177. else {
  100178. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  100179. width: blurTextureWidth,
  100180. height: blurTextureHeight
  100181. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100182. this._horizontalBlurPostprocess.width = blurTextureWidth;
  100183. this._horizontalBlurPostprocess.height = blurTextureHeight;
  100184. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100185. effect.setTexture("textureSampler", _this._mainTexture);
  100186. });
  100187. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  100188. width: blurTextureWidth,
  100189. height: blurTextureHeight
  100190. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100191. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100192. }
  100193. this._mainTexture.onAfterUnbindObservable.add(function () {
  100194. _this.onBeforeBlurObservable.notifyObservers(_this);
  100195. var internalTexture = _this._blurTexture.getInternalTexture();
  100196. if (internalTexture) {
  100197. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  100198. }
  100199. _this.onAfterBlurObservable.notifyObservers(_this);
  100200. });
  100201. // Prevent autoClear.
  100202. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100203. };
  100204. /**
  100205. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100206. */
  100207. HighlightLayer.prototype.needStencil = function () {
  100208. return true;
  100209. };
  100210. /**
  100211. * Checks for the readiness of the element composing the layer.
  100212. * @param subMesh the mesh to check for
  100213. * @param useInstances specify wether or not to use instances to render the mesh
  100214. * @param emissiveTexture the associated emissive texture used to generate the glow
  100215. * @return true if ready otherwise, false
  100216. */
  100217. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  100218. var material = subMesh.getMaterial();
  100219. var mesh = subMesh.getRenderingMesh();
  100220. if (!material || !mesh || !this._meshes) {
  100221. return false;
  100222. }
  100223. var emissiveTexture = null;
  100224. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100225. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100226. emissiveTexture = material.emissiveTexture;
  100227. }
  100228. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100229. };
  100230. /**
  100231. * Implementation specific of rendering the generating effect on the main canvas.
  100232. * @param effect The effect used to render through
  100233. */
  100234. HighlightLayer.prototype._internalRender = function (effect) {
  100235. // Texture
  100236. effect.setTexture("textureSampler", this._blurTexture);
  100237. // Cache
  100238. var engine = this._engine;
  100239. var previousStencilBuffer = engine.getStencilBuffer();
  100240. var previousStencilFunction = engine.getStencilFunction();
  100241. var previousStencilMask = engine.getStencilMask();
  100242. var previousStencilOperationPass = engine.getStencilOperationPass();
  100243. var previousStencilOperationFail = engine.getStencilOperationFail();
  100244. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  100245. var previousStencilReference = engine.getStencilFunctionReference();
  100246. // Stencil operations
  100247. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  100248. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  100249. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  100250. // Draw order
  100251. engine.setStencilMask(0x00);
  100252. engine.setStencilBuffer(true);
  100253. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  100254. // 2 passes inner outer
  100255. if (this.outerGlow) {
  100256. effect.setFloat("offset", 0);
  100257. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  100258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100259. }
  100260. if (this.innerGlow) {
  100261. effect.setFloat("offset", 1);
  100262. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  100263. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100264. }
  100265. // Restore Cache
  100266. engine.setStencilFunction(previousStencilFunction);
  100267. engine.setStencilMask(previousStencilMask);
  100268. engine.setStencilBuffer(previousStencilBuffer);
  100269. engine.setStencilOperationPass(previousStencilOperationPass);
  100270. engine.setStencilOperationFail(previousStencilOperationFail);
  100271. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  100272. engine.setStencilFunctionReference(previousStencilReference);
  100273. };
  100274. /**
  100275. * Returns true if the layer contains information to display, otherwise false.
  100276. */
  100277. HighlightLayer.prototype.shouldRender = function () {
  100278. if (_super.prototype.shouldRender.call(this)) {
  100279. return this._meshes ? true : false;
  100280. }
  100281. return false;
  100282. };
  100283. /**
  100284. * Returns true if the mesh should render, otherwise false.
  100285. * @param mesh The mesh to render
  100286. * @returns true if it should render otherwise false
  100287. */
  100288. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  100289. // Excluded Mesh
  100290. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  100291. return false;
  100292. }
  100293. ;
  100294. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100295. return false;
  100296. }
  100297. return true;
  100298. };
  100299. /**
  100300. * Sets the required values for both the emissive texture and and the main color.
  100301. */
  100302. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100303. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100304. if (highlightLayerMesh) {
  100305. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  100306. }
  100307. else {
  100308. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100309. }
  100310. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100311. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100312. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  100313. }
  100314. else {
  100315. this._emissiveTextureAndColor.texture = null;
  100316. }
  100317. };
  100318. /**
  100319. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  100320. * @param mesh The mesh to exclude from the highlight layer
  100321. */
  100322. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  100323. if (!this._excludedMeshes) {
  100324. return;
  100325. }
  100326. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100327. if (!meshExcluded) {
  100328. this._excludedMeshes[mesh.uniqueId] = {
  100329. mesh: mesh,
  100330. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  100331. mesh.getEngine().setStencilBuffer(false);
  100332. }),
  100333. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  100334. mesh.getEngine().setStencilBuffer(true);
  100335. }),
  100336. };
  100337. }
  100338. };
  100339. /**
  100340. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  100341. * @param mesh The mesh to highlight
  100342. */
  100343. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  100344. if (!this._excludedMeshes) {
  100345. return;
  100346. }
  100347. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100348. if (meshExcluded) {
  100349. if (meshExcluded.beforeRender) {
  100350. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  100351. }
  100352. if (meshExcluded.afterRender) {
  100353. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  100354. }
  100355. }
  100356. this._excludedMeshes[mesh.uniqueId] = null;
  100357. };
  100358. /**
  100359. * Determine if a given mesh will be highlighted by the current HighlightLayer
  100360. * @param mesh mesh to test
  100361. * @returns true if the mesh will be highlighted by the current HighlightLayer
  100362. */
  100363. HighlightLayer.prototype.hasMesh = function (mesh) {
  100364. if (!this._meshes) {
  100365. return false;
  100366. }
  100367. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100368. return false;
  100369. }
  100370. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  100371. };
  100372. /**
  100373. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  100374. * @param mesh The mesh to highlight
  100375. * @param color The color of the highlight
  100376. * @param glowEmissiveOnly Extract the glow from the emissive texture
  100377. */
  100378. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  100379. var _this = this;
  100380. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  100381. if (!this._meshes) {
  100382. return;
  100383. }
  100384. var meshHighlight = this._meshes[mesh.uniqueId];
  100385. if (meshHighlight) {
  100386. meshHighlight.color = color;
  100387. }
  100388. else {
  100389. this._meshes[mesh.uniqueId] = {
  100390. mesh: mesh,
  100391. color: color,
  100392. // Lambda required for capture due to Observable this context
  100393. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  100394. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  100395. _this._defaultStencilReference(mesh);
  100396. }
  100397. else {
  100398. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  100399. }
  100400. }),
  100401. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  100402. glowEmissiveOnly: glowEmissiveOnly
  100403. };
  100404. mesh.onDisposeObservable.add(function () {
  100405. _this._disposeMesh(mesh);
  100406. });
  100407. }
  100408. this._shouldRender = true;
  100409. };
  100410. /**
  100411. * Remove a mesh from the highlight layer in order to make it stop glowing.
  100412. * @param mesh The mesh to highlight
  100413. */
  100414. HighlightLayer.prototype.removeMesh = function (mesh) {
  100415. if (!this._meshes) {
  100416. return;
  100417. }
  100418. var meshHighlight = this._meshes[mesh.uniqueId];
  100419. if (meshHighlight) {
  100420. if (meshHighlight.observerHighlight) {
  100421. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100422. }
  100423. if (meshHighlight.observerDefault) {
  100424. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100425. }
  100426. delete this._meshes[mesh.uniqueId];
  100427. }
  100428. this._shouldRender = false;
  100429. for (var meshHighlightToCheck in this._meshes) {
  100430. if (this._meshes[meshHighlightToCheck]) {
  100431. this._shouldRender = true;
  100432. break;
  100433. }
  100434. }
  100435. };
  100436. /**
  100437. * Force the stencil to the normal expected value for none glowing parts
  100438. */
  100439. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  100440. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  100441. };
  100442. /**
  100443. * Free any resources and references associated to a mesh.
  100444. * Internal use
  100445. * @param mesh The mesh to free.
  100446. * @hidden
  100447. */
  100448. HighlightLayer.prototype._disposeMesh = function (mesh) {
  100449. this.removeMesh(mesh);
  100450. this.removeExcludedMesh(mesh);
  100451. };
  100452. /**
  100453. * Dispose the highlight layer and free resources.
  100454. */
  100455. HighlightLayer.prototype.dispose = function () {
  100456. if (this._meshes) {
  100457. // Clean mesh references
  100458. for (var id in this._meshes) {
  100459. var meshHighlight = this._meshes[id];
  100460. if (meshHighlight && meshHighlight.mesh) {
  100461. if (meshHighlight.observerHighlight) {
  100462. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100463. }
  100464. if (meshHighlight.observerDefault) {
  100465. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100466. }
  100467. }
  100468. }
  100469. this._meshes = null;
  100470. }
  100471. if (this._excludedMeshes) {
  100472. for (var id in this._excludedMeshes) {
  100473. var meshHighlight = this._excludedMeshes[id];
  100474. if (meshHighlight) {
  100475. if (meshHighlight.beforeRender) {
  100476. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  100477. }
  100478. if (meshHighlight.afterRender) {
  100479. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  100480. }
  100481. }
  100482. }
  100483. this._excludedMeshes = null;
  100484. }
  100485. _super.prototype.dispose.call(this);
  100486. };
  100487. /**
  100488. * Gets the class name of the effect layer
  100489. * @returns the string with the class name of the effect layer
  100490. */
  100491. HighlightLayer.prototype.getClassName = function () {
  100492. return "HighlightLayer";
  100493. };
  100494. /**
  100495. * Serializes this Highlight layer
  100496. * @returns a serialized Highlight layer object
  100497. */
  100498. HighlightLayer.prototype.serialize = function () {
  100499. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100500. serializationObject.customType = "BABYLON.HighlightLayer";
  100501. // Highlighted meshes
  100502. serializationObject.meshes = [];
  100503. if (this._meshes) {
  100504. for (var m in this._meshes) {
  100505. var mesh = this._meshes[m];
  100506. if (mesh) {
  100507. serializationObject.meshes.push({
  100508. glowEmissiveOnly: mesh.glowEmissiveOnly,
  100509. color: mesh.color.asArray(),
  100510. meshId: mesh.mesh.id
  100511. });
  100512. }
  100513. }
  100514. }
  100515. // Excluded meshes
  100516. serializationObject.excludedMeshes = [];
  100517. if (this._excludedMeshes) {
  100518. for (var e in this._excludedMeshes) {
  100519. var excludedMesh = this._excludedMeshes[e];
  100520. if (excludedMesh) {
  100521. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  100522. }
  100523. }
  100524. }
  100525. return serializationObject;
  100526. };
  100527. /**
  100528. * Creates a Highlight layer from parsed Highlight layer data
  100529. * @param parsedHightlightLayer defines the Highlight layer data
  100530. * @param scene defines the current scene
  100531. * @param rootUrl defines the root URL containing the Highlight layer information
  100532. * @returns a parsed Highlight layer
  100533. */
  100534. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  100535. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  100536. var index;
  100537. // Excluded meshes
  100538. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  100539. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  100540. if (mesh) {
  100541. hl.addExcludedMesh(mesh);
  100542. }
  100543. }
  100544. // Included meshes
  100545. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  100546. var highlightedMesh = parsedHightlightLayer.meshes[index];
  100547. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  100548. if (mesh) {
  100549. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  100550. }
  100551. }
  100552. return hl;
  100553. };
  100554. /**
  100555. * Effect Name of the highlight layer.
  100556. */
  100557. HighlightLayer.EffectName = "HighlightLayer";
  100558. /**
  100559. * The neutral color used during the preparation of the glow effect.
  100560. * This is black by default as the blend operation is a blend operation.
  100561. */
  100562. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  100563. /**
  100564. * Stencil value used for glowing meshes.
  100565. */
  100566. HighlightLayer.GlowingMeshStencilReference = 0x02;
  100567. /**
  100568. * Stencil value used for the other meshes in the scene.
  100569. */
  100570. HighlightLayer.NormalMeshStencilReference = 0x01;
  100571. __decorate([
  100572. BABYLON.serialize()
  100573. ], HighlightLayer.prototype, "innerGlow", void 0);
  100574. __decorate([
  100575. BABYLON.serialize()
  100576. ], HighlightLayer.prototype, "outerGlow", void 0);
  100577. __decorate([
  100578. BABYLON.serialize()
  100579. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  100580. __decorate([
  100581. BABYLON.serialize()
  100582. ], HighlightLayer.prototype, "blurVerticalSize", null);
  100583. __decorate([
  100584. BABYLON.serialize("options")
  100585. ], HighlightLayer.prototype, "_options", void 0);
  100586. return HighlightLayer;
  100587. }(BABYLON.EffectLayer));
  100588. BABYLON.HighlightLayer = HighlightLayer;
  100589. })(BABYLON || (BABYLON = {}));
  100590. //# sourceMappingURL=babylon.highlightLayer.js.map
  100591. var BABYLON;
  100592. (function (BABYLON) {
  100593. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  100594. for (var index = 0; index < this.effectLayers.length; index++) {
  100595. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  100596. return this.effectLayers[index];
  100597. }
  100598. }
  100599. return null;
  100600. };
  100601. /**
  100602. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  100603. *
  100604. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100605. * glowy meshes to your scene.
  100606. *
  100607. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  100608. */
  100609. var GlowLayer = /** @class */ (function (_super) {
  100610. __extends(GlowLayer, _super);
  100611. /**
  100612. * Instantiates a new glow Layer and references it to the scene.
  100613. * @param name The name of the layer
  100614. * @param scene The scene to use the layer in
  100615. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  100616. */
  100617. function GlowLayer(name, scene, options) {
  100618. var _this = _super.call(this, name, scene) || this;
  100619. _this._intensity = 1.0;
  100620. _this._includedOnlyMeshes = [];
  100621. _this._excludedMeshes = [];
  100622. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  100623. // Adapt options
  100624. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  100625. // Initialize the layer
  100626. _this._init({
  100627. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  100628. camera: _this._options.camera,
  100629. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100630. mainTextureRatio: _this._options.mainTextureRatio,
  100631. renderingGroupId: _this._options.renderingGroupId
  100632. });
  100633. return _this;
  100634. }
  100635. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  100636. /**
  100637. * Gets the kernel size of the blur.
  100638. */
  100639. get: function () {
  100640. return this._horizontalBlurPostprocess1.kernel;
  100641. },
  100642. /**
  100643. * Sets the kernel size of the blur.
  100644. */
  100645. set: function (value) {
  100646. this._horizontalBlurPostprocess1.kernel = value;
  100647. this._verticalBlurPostprocess1.kernel = value;
  100648. this._horizontalBlurPostprocess2.kernel = value;
  100649. this._verticalBlurPostprocess2.kernel = value;
  100650. },
  100651. enumerable: true,
  100652. configurable: true
  100653. });
  100654. Object.defineProperty(GlowLayer.prototype, "intensity", {
  100655. /**
  100656. * Gets the glow intensity.
  100657. */
  100658. get: function () {
  100659. return this._intensity;
  100660. },
  100661. /**
  100662. * Sets the glow intensity.
  100663. */
  100664. set: function (value) {
  100665. this._intensity = value;
  100666. },
  100667. enumerable: true,
  100668. configurable: true
  100669. });
  100670. /**
  100671. * Get the effect name of the layer.
  100672. * @return The effect name
  100673. */
  100674. GlowLayer.prototype.getEffectName = function () {
  100675. return GlowLayer.EffectName;
  100676. };
  100677. /**
  100678. * Create the merge effect. This is the shader use to blit the information back
  100679. * to the main canvas at the end of the scene rendering.
  100680. */
  100681. GlowLayer.prototype._createMergeEffect = function () {
  100682. // Effect
  100683. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  100684. };
  100685. /**
  100686. * Creates the render target textures and post processes used in the glow layer.
  100687. */
  100688. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  100689. var _this = this;
  100690. var blurTextureWidth = this._mainTextureDesiredSize.width;
  100691. var blurTextureHeight = this._mainTextureDesiredSize.height;
  100692. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100693. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100694. var textureType = 0;
  100695. if (this._engine.getCaps().textureHalfFloatRender) {
  100696. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100697. }
  100698. else {
  100699. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100700. }
  100701. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  100702. width: blurTextureWidth,
  100703. height: blurTextureHeight
  100704. }, this._scene, false, true, textureType);
  100705. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100706. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100707. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100708. this._blurTexture1.renderParticles = false;
  100709. this._blurTexture1.ignoreCameraViewport = true;
  100710. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  100711. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  100712. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  100713. width: blurTextureWidth2,
  100714. height: blurTextureHeight2
  100715. }, this._scene, false, true, textureType);
  100716. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100717. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100718. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100719. this._blurTexture2.renderParticles = false;
  100720. this._blurTexture2.ignoreCameraViewport = true;
  100721. this._textures = [this._blurTexture1, this._blurTexture2];
  100722. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  100723. width: blurTextureWidth,
  100724. height: blurTextureHeight
  100725. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100726. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  100727. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  100728. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  100729. effect.setTexture("textureSampler", _this._mainTexture);
  100730. });
  100731. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  100732. width: blurTextureWidth,
  100733. height: blurTextureHeight
  100734. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100735. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  100736. width: blurTextureWidth2,
  100737. height: blurTextureHeight2
  100738. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100739. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  100740. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  100741. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  100742. effect.setTexture("textureSampler", _this._blurTexture1);
  100743. });
  100744. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  100745. width: blurTextureWidth2,
  100746. height: blurTextureHeight2
  100747. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100748. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  100749. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  100750. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  100751. this._mainTexture.samples = this._options.mainTextureSamples;
  100752. this._mainTexture.onAfterUnbindObservable.add(function () {
  100753. var internalTexture = _this._blurTexture1.getInternalTexture();
  100754. if (internalTexture) {
  100755. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  100756. internalTexture = _this._blurTexture2.getInternalTexture();
  100757. if (internalTexture) {
  100758. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  100759. }
  100760. }
  100761. });
  100762. // Prevent autoClear.
  100763. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100764. };
  100765. /**
  100766. * Checks for the readiness of the element composing the layer.
  100767. * @param subMesh the mesh to check for
  100768. * @param useInstances specify wether or not to use instances to render the mesh
  100769. * @param emissiveTexture the associated emissive texture used to generate the glow
  100770. * @return true if ready otherwise, false
  100771. */
  100772. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  100773. var material = subMesh.getMaterial();
  100774. var mesh = subMesh.getRenderingMesh();
  100775. if (!material || !mesh) {
  100776. return false;
  100777. }
  100778. var emissiveTexture = material.emissiveTexture;
  100779. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100780. };
  100781. /**
  100782. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100783. */
  100784. GlowLayer.prototype.needStencil = function () {
  100785. return false;
  100786. };
  100787. /**
  100788. * Implementation specific of rendering the generating effect on the main canvas.
  100789. * @param effect The effect used to render through
  100790. */
  100791. GlowLayer.prototype._internalRender = function (effect) {
  100792. // Texture
  100793. effect.setTexture("textureSampler", this._blurTexture1);
  100794. effect.setTexture("textureSampler2", this._blurTexture2);
  100795. effect.setFloat("offset", this._intensity);
  100796. // Cache
  100797. var engine = this._engine;
  100798. var previousStencilBuffer = engine.getStencilBuffer();
  100799. // Draw order
  100800. engine.setStencilBuffer(false);
  100801. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100802. // Draw order
  100803. engine.setStencilBuffer(previousStencilBuffer);
  100804. };
  100805. /**
  100806. * Sets the required values for both the emissive texture and and the main color.
  100807. */
  100808. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100809. var textureLevel = 1.0;
  100810. if (this.customEmissiveTextureSelector) {
  100811. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  100812. }
  100813. else {
  100814. if (material) {
  100815. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100816. if (this._emissiveTextureAndColor.texture) {
  100817. textureLevel = this._emissiveTextureAndColor.texture.level;
  100818. }
  100819. }
  100820. else {
  100821. this._emissiveTextureAndColor.texture = null;
  100822. }
  100823. }
  100824. if (this.customEmissiveColorSelector) {
  100825. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  100826. }
  100827. else {
  100828. if (material.emissiveColor) {
  100829. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  100830. }
  100831. else {
  100832. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100833. }
  100834. }
  100835. };
  100836. /**
  100837. * Returns true if the mesh should render, otherwise false.
  100838. * @param mesh The mesh to render
  100839. * @returns true if it should render otherwise false
  100840. */
  100841. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  100842. return this.hasMesh(mesh);
  100843. };
  100844. /**
  100845. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  100846. * @param mesh The mesh to exclude from the glow layer
  100847. */
  100848. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  100849. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  100850. this._excludedMeshes.push(mesh.uniqueId);
  100851. }
  100852. };
  100853. /**
  100854. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  100855. * @param mesh The mesh to remove
  100856. */
  100857. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  100858. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  100859. if (index !== -1) {
  100860. this._excludedMeshes.splice(index, 1);
  100861. }
  100862. };
  100863. /**
  100864. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  100865. * @param mesh The mesh to include in the glow layer
  100866. */
  100867. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  100868. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  100869. this._includedOnlyMeshes.push(mesh.uniqueId);
  100870. }
  100871. };
  100872. /**
  100873. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  100874. * @param mesh The mesh to remove
  100875. */
  100876. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  100877. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  100878. if (index !== -1) {
  100879. this._includedOnlyMeshes.splice(index, 1);
  100880. }
  100881. };
  100882. /**
  100883. * Determine if a given mesh will be used in the glow layer
  100884. * @param mesh The mesh to test
  100885. * @returns true if the mesh will be highlighted by the current glow layer
  100886. */
  100887. GlowLayer.prototype.hasMesh = function (mesh) {
  100888. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100889. return false;
  100890. }
  100891. // Included Mesh
  100892. if (this._includedOnlyMeshes.length) {
  100893. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  100894. }
  100895. ;
  100896. // Excluded Mesh
  100897. if (this._excludedMeshes.length) {
  100898. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  100899. }
  100900. ;
  100901. return true;
  100902. };
  100903. /**
  100904. * Free any resources and references associated to a mesh.
  100905. * Internal use
  100906. * @param mesh The mesh to free.
  100907. * @hidden
  100908. */
  100909. GlowLayer.prototype._disposeMesh = function (mesh) {
  100910. this.removeIncludedOnlyMesh(mesh);
  100911. this.removeExcludedMesh(mesh);
  100912. };
  100913. /**
  100914. * Gets the class name of the effect layer
  100915. * @returns the string with the class name of the effect layer
  100916. */
  100917. GlowLayer.prototype.getClassName = function () {
  100918. return "GlowLayer";
  100919. };
  100920. /**
  100921. * Serializes this glow layer
  100922. * @returns a serialized glow layer object
  100923. */
  100924. GlowLayer.prototype.serialize = function () {
  100925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100926. serializationObject.customType = "BABYLON.GlowLayer";
  100927. var index;
  100928. // Included meshes
  100929. serializationObject.includedMeshes = [];
  100930. if (this._includedOnlyMeshes.length) {
  100931. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  100932. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  100933. if (mesh) {
  100934. serializationObject.includedMeshes.push(mesh.id);
  100935. }
  100936. }
  100937. }
  100938. // Excluded meshes
  100939. serializationObject.excludedMeshes = [];
  100940. if (this._excludedMeshes.length) {
  100941. for (index = 0; index < this._excludedMeshes.length; index++) {
  100942. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  100943. if (mesh) {
  100944. serializationObject.excludedMeshes.push(mesh.id);
  100945. }
  100946. }
  100947. }
  100948. return serializationObject;
  100949. };
  100950. /**
  100951. * Creates a Glow Layer from parsed glow layer data
  100952. * @param parsedGlowLayer defines glow layer data
  100953. * @param scene defines the current scene
  100954. * @param rootUrl defines the root URL containing the glow layer information
  100955. * @returns a parsed Glow Layer
  100956. */
  100957. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  100958. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  100959. var index;
  100960. // Excluded meshes
  100961. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  100962. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  100963. if (mesh) {
  100964. gl.addExcludedMesh(mesh);
  100965. }
  100966. }
  100967. // Included meshes
  100968. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  100969. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  100970. if (mesh) {
  100971. gl.addIncludedOnlyMesh(mesh);
  100972. }
  100973. }
  100974. return gl;
  100975. };
  100976. /**
  100977. * Effect Name of the layer.
  100978. */
  100979. GlowLayer.EffectName = "GlowLayer";
  100980. /**
  100981. * The default blur kernel size used for the glow.
  100982. */
  100983. GlowLayer.DefaultBlurKernelSize = 32;
  100984. /**
  100985. * The default texture size ratio used for the glow.
  100986. */
  100987. GlowLayer.DefaultTextureRatio = 0.5;
  100988. __decorate([
  100989. BABYLON.serialize()
  100990. ], GlowLayer.prototype, "blurKernelSize", null);
  100991. __decorate([
  100992. BABYLON.serialize()
  100993. ], GlowLayer.prototype, "intensity", null);
  100994. __decorate([
  100995. BABYLON.serialize("options")
  100996. ], GlowLayer.prototype, "_options", void 0);
  100997. return GlowLayer;
  100998. }(BABYLON.EffectLayer));
  100999. BABYLON.GlowLayer = GlowLayer;
  101000. })(BABYLON || (BABYLON = {}));
  101001. //# sourceMappingURL=babylon.glowLayer.js.map
  101002. var BABYLON;
  101003. (function (BABYLON) {
  101004. /**
  101005. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  101006. */
  101007. var AssetTaskState;
  101008. (function (AssetTaskState) {
  101009. /**
  101010. * Initialization
  101011. */
  101012. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  101013. /**
  101014. * Running
  101015. */
  101016. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  101017. /**
  101018. * Done
  101019. */
  101020. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  101021. /**
  101022. * Error
  101023. */
  101024. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  101025. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  101026. /**
  101027. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  101028. */
  101029. var AbstractAssetTask = /** @class */ (function () {
  101030. /**
  101031. * Creates a new {BABYLON.AssetsManager}
  101032. * @param name defines the name of the task
  101033. */
  101034. function AbstractAssetTask(
  101035. /**
  101036. * Task name
  101037. */ name) {
  101038. this.name = name;
  101039. this._isCompleted = false;
  101040. this._taskState = AssetTaskState.INIT;
  101041. }
  101042. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  101043. /**
  101044. * Get if the task is completed
  101045. */
  101046. get: function () {
  101047. return this._isCompleted;
  101048. },
  101049. enumerable: true,
  101050. configurable: true
  101051. });
  101052. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  101053. /**
  101054. * Gets the current state of the task
  101055. */
  101056. get: function () {
  101057. return this._taskState;
  101058. },
  101059. enumerable: true,
  101060. configurable: true
  101061. });
  101062. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  101063. /**
  101064. * Gets the current error object (if task is in error)
  101065. */
  101066. get: function () {
  101067. return this._errorObject;
  101068. },
  101069. enumerable: true,
  101070. configurable: true
  101071. });
  101072. /**
  101073. * Internal only
  101074. * @hidden
  101075. */
  101076. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  101077. if (this._errorObject) {
  101078. return;
  101079. }
  101080. this._errorObject = {
  101081. message: message,
  101082. exception: exception
  101083. };
  101084. };
  101085. /**
  101086. * Execute the current task
  101087. * @param scene defines the scene where you want your assets to be loaded
  101088. * @param onSuccess is a callback called when the task is successfully executed
  101089. * @param onError is a callback called if an error occurs
  101090. */
  101091. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101092. var _this = this;
  101093. this._taskState = AssetTaskState.RUNNING;
  101094. this.runTask(scene, function () {
  101095. _this.onDoneCallback(onSuccess, onError);
  101096. }, function (msg, exception) {
  101097. _this.onErrorCallback(onError, msg, exception);
  101098. });
  101099. };
  101100. /**
  101101. * Execute the current task
  101102. * @param scene defines the scene where you want your assets to be loaded
  101103. * @param onSuccess is a callback called when the task is successfully executed
  101104. * @param onError is a callback called if an error occurs
  101105. */
  101106. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101107. throw new Error("runTask is not implemented");
  101108. };
  101109. /**
  101110. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  101111. * This can be used with failed tasks that have the reason for failure fixed.
  101112. */
  101113. AbstractAssetTask.prototype.reset = function () {
  101114. this._taskState = AssetTaskState.INIT;
  101115. };
  101116. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  101117. this._taskState = AssetTaskState.ERROR;
  101118. this._errorObject = {
  101119. message: message,
  101120. exception: exception
  101121. };
  101122. if (this.onError) {
  101123. this.onError(this, message, exception);
  101124. }
  101125. onError();
  101126. };
  101127. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  101128. try {
  101129. this._taskState = AssetTaskState.DONE;
  101130. this._isCompleted = true;
  101131. if (this.onSuccess) {
  101132. this.onSuccess(this);
  101133. }
  101134. onSuccess();
  101135. }
  101136. catch (e) {
  101137. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  101138. }
  101139. };
  101140. return AbstractAssetTask;
  101141. }());
  101142. BABYLON.AbstractAssetTask = AbstractAssetTask;
  101143. /**
  101144. * Class used to share progress information about assets loading
  101145. */
  101146. var AssetsProgressEvent = /** @class */ (function () {
  101147. /**
  101148. * Creates a {BABYLON.AssetsProgressEvent}
  101149. * @param remainingCount defines the number of remaining tasks to process
  101150. * @param totalCount defines the total number of tasks
  101151. * @param task defines the task that was just processed
  101152. */
  101153. function AssetsProgressEvent(remainingCount, totalCount, task) {
  101154. this.remainingCount = remainingCount;
  101155. this.totalCount = totalCount;
  101156. this.task = task;
  101157. }
  101158. return AssetsProgressEvent;
  101159. }());
  101160. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  101161. /**
  101162. * Define a task used by {BABYLON.AssetsManager} to load meshes
  101163. */
  101164. var MeshAssetTask = /** @class */ (function (_super) {
  101165. __extends(MeshAssetTask, _super);
  101166. /**
  101167. * Creates a new {BABYLON.MeshAssetTask}
  101168. * @param name defines the name of the task
  101169. * @param meshesNames defines the list of mesh's names you want to load
  101170. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  101171. * @param sceneFilename defines the filename of the scene to load from
  101172. */
  101173. function MeshAssetTask(
  101174. /**
  101175. * Defines the name of the task
  101176. */
  101177. name,
  101178. /**
  101179. * Defines the list of mesh's names you want to load
  101180. */
  101181. meshesNames,
  101182. /**
  101183. * Defines the root url to use as a base to load your meshes and associated resources
  101184. */
  101185. rootUrl,
  101186. /**
  101187. * Defines the filename of the scene to load from
  101188. */
  101189. sceneFilename) {
  101190. var _this = _super.call(this, name) || this;
  101191. _this.name = name;
  101192. _this.meshesNames = meshesNames;
  101193. _this.rootUrl = rootUrl;
  101194. _this.sceneFilename = sceneFilename;
  101195. return _this;
  101196. }
  101197. /**
  101198. * Execute the current task
  101199. * @param scene defines the scene where you want your assets to be loaded
  101200. * @param onSuccess is a callback called when the task is successfully executed
  101201. * @param onError is a callback called if an error occurs
  101202. */
  101203. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101204. var _this = this;
  101205. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  101206. _this.loadedMeshes = meshes;
  101207. _this.loadedParticleSystems = particleSystems;
  101208. _this.loadedSkeletons = skeletons;
  101209. onSuccess();
  101210. }, null, function (scene, message, exception) {
  101211. onError(message, exception);
  101212. });
  101213. };
  101214. return MeshAssetTask;
  101215. }(AbstractAssetTask));
  101216. BABYLON.MeshAssetTask = MeshAssetTask;
  101217. /**
  101218. * Define a task used by {BABYLON.AssetsManager} to load text content
  101219. */
  101220. var TextFileAssetTask = /** @class */ (function (_super) {
  101221. __extends(TextFileAssetTask, _super);
  101222. /**
  101223. * Creates a new TextFileAssetTask object
  101224. * @param name defines the name of the task
  101225. * @param url defines the location of the file to load
  101226. */
  101227. function TextFileAssetTask(
  101228. /**
  101229. * Defines the name of the task
  101230. */
  101231. name,
  101232. /**
  101233. * Defines the location of the file to load
  101234. */
  101235. url) {
  101236. var _this = _super.call(this, name) || this;
  101237. _this.name = name;
  101238. _this.url = url;
  101239. return _this;
  101240. }
  101241. /**
  101242. * Execute the current task
  101243. * @param scene defines the scene where you want your assets to be loaded
  101244. * @param onSuccess is a callback called when the task is successfully executed
  101245. * @param onError is a callback called if an error occurs
  101246. */
  101247. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101248. var _this = this;
  101249. scene._loadFile(this.url, function (data) {
  101250. _this.text = data;
  101251. onSuccess();
  101252. }, undefined, false, false, function (request, exception) {
  101253. if (request) {
  101254. onError(request.status + " " + request.statusText, exception);
  101255. }
  101256. });
  101257. };
  101258. return TextFileAssetTask;
  101259. }(AbstractAssetTask));
  101260. BABYLON.TextFileAssetTask = TextFileAssetTask;
  101261. /**
  101262. * Define a task used by {BABYLON.AssetsManager} to load binary data
  101263. */
  101264. var BinaryFileAssetTask = /** @class */ (function (_super) {
  101265. __extends(BinaryFileAssetTask, _super);
  101266. /**
  101267. * Creates a new BinaryFileAssetTask object
  101268. * @param name defines the name of the new task
  101269. * @param url defines the location of the file to load
  101270. */
  101271. function BinaryFileAssetTask(
  101272. /**
  101273. * Defines the name of the task
  101274. */
  101275. name,
  101276. /**
  101277. * Defines the location of the file to load
  101278. */
  101279. url) {
  101280. var _this = _super.call(this, name) || this;
  101281. _this.name = name;
  101282. _this.url = url;
  101283. return _this;
  101284. }
  101285. /**
  101286. * Execute the current task
  101287. * @param scene defines the scene where you want your assets to be loaded
  101288. * @param onSuccess is a callback called when the task is successfully executed
  101289. * @param onError is a callback called if an error occurs
  101290. */
  101291. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101292. var _this = this;
  101293. scene._loadFile(this.url, function (data) {
  101294. _this.data = data;
  101295. onSuccess();
  101296. }, undefined, true, true, function (request, exception) {
  101297. if (request) {
  101298. onError(request.status + " " + request.statusText, exception);
  101299. }
  101300. });
  101301. };
  101302. return BinaryFileAssetTask;
  101303. }(AbstractAssetTask));
  101304. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  101305. /**
  101306. * Define a task used by {BABYLON.AssetsManager} to load images
  101307. */
  101308. var ImageAssetTask = /** @class */ (function (_super) {
  101309. __extends(ImageAssetTask, _super);
  101310. /**
  101311. * Creates a new ImageAssetTask
  101312. * @param name defines the name of the task
  101313. * @param url defines the location of the image to load
  101314. */
  101315. function ImageAssetTask(
  101316. /**
  101317. * Defines the name of the task
  101318. */
  101319. name,
  101320. /**
  101321. * Defines the location of the image to load
  101322. */
  101323. url) {
  101324. var _this = _super.call(this, name) || this;
  101325. _this.name = name;
  101326. _this.url = url;
  101327. return _this;
  101328. }
  101329. /**
  101330. * Execute the current task
  101331. * @param scene defines the scene where you want your assets to be loaded
  101332. * @param onSuccess is a callback called when the task is successfully executed
  101333. * @param onError is a callback called if an error occurs
  101334. */
  101335. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101336. var _this = this;
  101337. var img = new Image();
  101338. BABYLON.Tools.SetCorsBehavior(this.url, img);
  101339. img.onload = function () {
  101340. _this.image = img;
  101341. onSuccess();
  101342. };
  101343. img.onerror = function (err) {
  101344. onError("Error loading image", err);
  101345. };
  101346. img.src = this.url;
  101347. };
  101348. return ImageAssetTask;
  101349. }(AbstractAssetTask));
  101350. BABYLON.ImageAssetTask = ImageAssetTask;
  101351. /**
  101352. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  101353. */
  101354. var TextureAssetTask = /** @class */ (function (_super) {
  101355. __extends(TextureAssetTask, _super);
  101356. /**
  101357. * Creates a new TextureAssetTask object
  101358. * @param name defines the name of the task
  101359. * @param url defines the location of the file to load
  101360. * @param noMipmap defines if mipmap should not be generated (default is false)
  101361. * @param invertY defines if texture must be inverted on Y axis (default is false)
  101362. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101363. */
  101364. function TextureAssetTask(
  101365. /**
  101366. * Defines the name of the task
  101367. */
  101368. name,
  101369. /**
  101370. * Defines the location of the file to load
  101371. */
  101372. url,
  101373. /**
  101374. * Defines if mipmap should not be generated (default is false)
  101375. */
  101376. noMipmap,
  101377. /**
  101378. * Defines if texture must be inverted on Y axis (default is false)
  101379. */
  101380. invertY,
  101381. /**
  101382. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101383. */
  101384. samplingMode) {
  101385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101386. var _this = _super.call(this, name) || this;
  101387. _this.name = name;
  101388. _this.url = url;
  101389. _this.noMipmap = noMipmap;
  101390. _this.invertY = invertY;
  101391. _this.samplingMode = samplingMode;
  101392. return _this;
  101393. }
  101394. /**
  101395. * Execute the current task
  101396. * @param scene defines the scene where you want your assets to be loaded
  101397. * @param onSuccess is a callback called when the task is successfully executed
  101398. * @param onError is a callback called if an error occurs
  101399. */
  101400. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101401. var onload = function () {
  101402. onSuccess();
  101403. };
  101404. var onerror = function (message, exception) {
  101405. onError(message, exception);
  101406. };
  101407. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  101408. };
  101409. return TextureAssetTask;
  101410. }(AbstractAssetTask));
  101411. BABYLON.TextureAssetTask = TextureAssetTask;
  101412. /**
  101413. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  101414. */
  101415. var CubeTextureAssetTask = /** @class */ (function (_super) {
  101416. __extends(CubeTextureAssetTask, _super);
  101417. /**
  101418. * Creates a new CubeTextureAssetTask
  101419. * @param name defines the name of the task
  101420. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101421. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101422. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101423. * @param files defines the explicit list of files (undefined by default)
  101424. */
  101425. function CubeTextureAssetTask(
  101426. /**
  101427. * Defines the name of the task
  101428. */
  101429. name,
  101430. /**
  101431. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101432. */
  101433. url,
  101434. /**
  101435. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101436. */
  101437. extensions,
  101438. /**
  101439. * Defines if mipmaps should not be generated (default is false)
  101440. */
  101441. noMipmap,
  101442. /**
  101443. * Defines the explicit list of files (undefined by default)
  101444. */
  101445. files) {
  101446. var _this = _super.call(this, name) || this;
  101447. _this.name = name;
  101448. _this.url = url;
  101449. _this.extensions = extensions;
  101450. _this.noMipmap = noMipmap;
  101451. _this.files = files;
  101452. return _this;
  101453. }
  101454. /**
  101455. * Execute the current task
  101456. * @param scene defines the scene where you want your assets to be loaded
  101457. * @param onSuccess is a callback called when the task is successfully executed
  101458. * @param onError is a callback called if an error occurs
  101459. */
  101460. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101461. var onload = function () {
  101462. onSuccess();
  101463. };
  101464. var onerror = function (message, exception) {
  101465. onError(message, exception);
  101466. };
  101467. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  101468. };
  101469. return CubeTextureAssetTask;
  101470. }(AbstractAssetTask));
  101471. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  101472. /**
  101473. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  101474. */
  101475. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  101476. __extends(HDRCubeTextureAssetTask, _super);
  101477. /**
  101478. * Creates a new HDRCubeTextureAssetTask object
  101479. * @param name defines the name of the task
  101480. * @param url defines the location of the file to load
  101481. * @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.
  101482. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101483. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101484. * @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)
  101485. * @param reserved Internal use only
  101486. */
  101487. function HDRCubeTextureAssetTask(
  101488. /**
  101489. * Defines the name of the task
  101490. */
  101491. name,
  101492. /**
  101493. * Defines the location of the file to load
  101494. */
  101495. url,
  101496. /**
  101497. * Defines the desired size (the more it increases the longer the generation will be)
  101498. */
  101499. size,
  101500. /**
  101501. * Defines if mipmaps should not be generated (default is false)
  101502. */
  101503. noMipmap,
  101504. /**
  101505. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101506. */
  101507. generateHarmonics,
  101508. /**
  101509. * 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)
  101510. */
  101511. gammaSpace,
  101512. /**
  101513. * Internal Use Only
  101514. */
  101515. reserved) {
  101516. if (noMipmap === void 0) { noMipmap = false; }
  101517. if (generateHarmonics === void 0) { generateHarmonics = true; }
  101518. if (gammaSpace === void 0) { gammaSpace = false; }
  101519. if (reserved === void 0) { reserved = false; }
  101520. var _this = _super.call(this, name) || this;
  101521. _this.name = name;
  101522. _this.url = url;
  101523. _this.size = size;
  101524. _this.noMipmap = noMipmap;
  101525. _this.generateHarmonics = generateHarmonics;
  101526. _this.gammaSpace = gammaSpace;
  101527. _this.reserved = reserved;
  101528. return _this;
  101529. }
  101530. /**
  101531. * Execute the current task
  101532. * @param scene defines the scene where you want your assets to be loaded
  101533. * @param onSuccess is a callback called when the task is successfully executed
  101534. * @param onError is a callback called if an error occurs
  101535. */
  101536. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101537. var onload = function () {
  101538. onSuccess();
  101539. };
  101540. var onerror = function (message, exception) {
  101541. onError(message, exception);
  101542. };
  101543. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  101544. };
  101545. return HDRCubeTextureAssetTask;
  101546. }(AbstractAssetTask));
  101547. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  101548. /**
  101549. * This class can be used to easily import assets into a scene
  101550. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  101551. */
  101552. var AssetsManager = /** @class */ (function () {
  101553. /**
  101554. * Creates a new AssetsManager
  101555. * @param scene defines the scene to work on
  101556. */
  101557. function AssetsManager(scene) {
  101558. this._isLoading = false;
  101559. this._tasks = new Array();
  101560. this._waitingTasksCount = 0;
  101561. this._totalTasksCount = 0;
  101562. /**
  101563. * Observable called when all tasks are processed
  101564. */
  101565. this.onTaskSuccessObservable = new BABYLON.Observable();
  101566. /**
  101567. * Observable called when a task had an error
  101568. */
  101569. this.onTaskErrorObservable = new BABYLON.Observable();
  101570. /**
  101571. * Observable called when a task is successful
  101572. */
  101573. this.onTasksDoneObservable = new BABYLON.Observable();
  101574. /**
  101575. * Observable called when a task is done (whatever the result is)
  101576. */
  101577. this.onProgressObservable = new BABYLON.Observable();
  101578. /**
  101579. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  101580. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  101581. */
  101582. this.useDefaultLoadingScreen = true;
  101583. this._scene = scene;
  101584. }
  101585. /**
  101586. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  101587. * @param taskName defines the name of the new task
  101588. * @param meshesNames defines the name of meshes to load
  101589. * @param rootUrl defines the root url to use to locate files
  101590. * @param sceneFilename defines the filename of the scene file
  101591. * @returns a new {BABYLON.MeshAssetTask} object
  101592. */
  101593. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  101594. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  101595. this._tasks.push(task);
  101596. return task;
  101597. };
  101598. /**
  101599. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  101600. * @param taskName defines the name of the new task
  101601. * @param url defines the url of the file to load
  101602. * @returns a new {BABYLON.TextFileAssetTask} object
  101603. */
  101604. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  101605. var task = new TextFileAssetTask(taskName, url);
  101606. this._tasks.push(task);
  101607. return task;
  101608. };
  101609. /**
  101610. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  101611. * @param taskName defines the name of the new task
  101612. * @param url defines the url of the file to load
  101613. * @returns a new {BABYLON.BinaryFileAssetTask} object
  101614. */
  101615. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  101616. var task = new BinaryFileAssetTask(taskName, url);
  101617. this._tasks.push(task);
  101618. return task;
  101619. };
  101620. /**
  101621. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  101622. * @param taskName defines the name of the new task
  101623. * @param url defines the url of the file to load
  101624. * @returns a new {BABYLON.ImageAssetTask} object
  101625. */
  101626. AssetsManager.prototype.addImageTask = function (taskName, url) {
  101627. var task = new ImageAssetTask(taskName, url);
  101628. this._tasks.push(task);
  101629. return task;
  101630. };
  101631. /**
  101632. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  101633. * @param taskName defines the name of the new task
  101634. * @param url defines the url of the file to load
  101635. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  101636. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  101637. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  101638. * @returns a new {BABYLON.TextureAssetTask} object
  101639. */
  101640. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  101641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101642. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  101643. this._tasks.push(task);
  101644. return task;
  101645. };
  101646. /**
  101647. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  101648. * @param taskName defines the name of the new task
  101649. * @param url defines the url of the file to load
  101650. * @param extensions defines the extension to use to load the cube map (can be null)
  101651. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  101652. * @param files defines the list of files to load (can be null)
  101653. * @returns a new {BABYLON.CubeTextureAssetTask} object
  101654. */
  101655. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  101656. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  101657. this._tasks.push(task);
  101658. return task;
  101659. };
  101660. /**
  101661. *
  101662. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  101663. * @param taskName defines the name of the new task
  101664. * @param url defines the url of the file to load
  101665. * @param size defines the size you want for the cubemap (can be null)
  101666. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  101667. * @param generateHarmonics defines if you want to automatically generate (true by default)
  101668. * @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)
  101669. * @param reserved Internal use only
  101670. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  101671. */
  101672. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  101673. if (noMipmap === void 0) { noMipmap = false; }
  101674. if (generateHarmonics === void 0) { generateHarmonics = true; }
  101675. if (gammaSpace === void 0) { gammaSpace = false; }
  101676. if (reserved === void 0) { reserved = false; }
  101677. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  101678. this._tasks.push(task);
  101679. return task;
  101680. };
  101681. /**
  101682. * Remove a task from the assets manager.
  101683. * @param task the task to remove
  101684. */
  101685. AssetsManager.prototype.removeTask = function (task) {
  101686. var index = this._tasks.indexOf(task);
  101687. if (index > -1) {
  101688. this._tasks.splice(index, 1);
  101689. }
  101690. };
  101691. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  101692. this._waitingTasksCount--;
  101693. try {
  101694. if (this.onProgress) {
  101695. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  101696. }
  101697. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  101698. }
  101699. catch (e) {
  101700. BABYLON.Tools.Error("Error running progress callbacks.");
  101701. console.log(e);
  101702. }
  101703. if (this._waitingTasksCount === 0) {
  101704. try {
  101705. if (this.onFinish) {
  101706. this.onFinish(this._tasks);
  101707. }
  101708. // Let's remove successfull tasks
  101709. var currentTasks = this._tasks.slice();
  101710. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  101711. var task = currentTasks_1[_i];
  101712. if (task.taskState === AssetTaskState.DONE) {
  101713. var index = this._tasks.indexOf(task);
  101714. if (index > -1) {
  101715. this._tasks.splice(index, 1);
  101716. }
  101717. }
  101718. }
  101719. this.onTasksDoneObservable.notifyObservers(this._tasks);
  101720. }
  101721. catch (e) {
  101722. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  101723. console.log(e);
  101724. }
  101725. this._isLoading = false;
  101726. this._scene.getEngine().hideLoadingUI();
  101727. }
  101728. };
  101729. AssetsManager.prototype._runTask = function (task) {
  101730. var _this = this;
  101731. var done = function () {
  101732. try {
  101733. if (_this.onTaskSuccess) {
  101734. _this.onTaskSuccess(task);
  101735. }
  101736. _this.onTaskSuccessObservable.notifyObservers(task);
  101737. _this._decreaseWaitingTasksCount(task);
  101738. }
  101739. catch (e) {
  101740. error("Error executing task success callbacks", e);
  101741. }
  101742. };
  101743. var error = function (message, exception) {
  101744. task._setErrorObject(message, exception);
  101745. if (_this.onTaskError) {
  101746. _this.onTaskError(task);
  101747. }
  101748. _this.onTaskErrorObservable.notifyObservers(task);
  101749. _this._decreaseWaitingTasksCount(task);
  101750. };
  101751. task.run(this._scene, done, error);
  101752. };
  101753. /**
  101754. * Reset the {BABYLON.AssetsManager} and remove all tasks
  101755. * @return the current instance of the {BABYLON.AssetsManager}
  101756. */
  101757. AssetsManager.prototype.reset = function () {
  101758. this._isLoading = false;
  101759. this._tasks = new Array();
  101760. return this;
  101761. };
  101762. /**
  101763. * Start the loading process
  101764. * @return the current instance of the {BABYLON.AssetsManager}
  101765. */
  101766. AssetsManager.prototype.load = function () {
  101767. if (this._isLoading) {
  101768. return this;
  101769. }
  101770. this._isLoading = true;
  101771. this._waitingTasksCount = this._tasks.length;
  101772. this._totalTasksCount = this._tasks.length;
  101773. if (this._waitingTasksCount === 0) {
  101774. this._isLoading = false;
  101775. if (this.onFinish) {
  101776. this.onFinish(this._tasks);
  101777. }
  101778. this.onTasksDoneObservable.notifyObservers(this._tasks);
  101779. return this;
  101780. }
  101781. if (this.useDefaultLoadingScreen) {
  101782. this._scene.getEngine().displayLoadingUI();
  101783. }
  101784. for (var index = 0; index < this._tasks.length; index++) {
  101785. var task = this._tasks[index];
  101786. if (task.taskState === AssetTaskState.INIT) {
  101787. this._runTask(task);
  101788. }
  101789. }
  101790. return this;
  101791. };
  101792. return AssetsManager;
  101793. }());
  101794. BABYLON.AssetsManager = AssetsManager;
  101795. })(BABYLON || (BABYLON = {}));
  101796. //# sourceMappingURL=babylon.assetsManager.js.map
  101797. var BABYLON;
  101798. (function (BABYLON) {
  101799. var serializedGeometries = [];
  101800. var serializeGeometry = function (geometry, serializationGeometries) {
  101801. if (serializedGeometries[geometry.id]) {
  101802. return;
  101803. }
  101804. if (geometry.doNotSerialize) {
  101805. return;
  101806. }
  101807. if (geometry instanceof BABYLON.BoxGeometry) {
  101808. serializationGeometries.boxes.push(geometry.serialize());
  101809. }
  101810. else if (geometry instanceof BABYLON.SphereGeometry) {
  101811. serializationGeometries.spheres.push(geometry.serialize());
  101812. }
  101813. else if (geometry instanceof BABYLON.CylinderGeometry) {
  101814. serializationGeometries.cylinders.push(geometry.serialize());
  101815. }
  101816. else if (geometry instanceof BABYLON.TorusGeometry) {
  101817. serializationGeometries.toruses.push(geometry.serialize());
  101818. }
  101819. else if (geometry instanceof BABYLON.GroundGeometry) {
  101820. serializationGeometries.grounds.push(geometry.serialize());
  101821. }
  101822. else if (geometry instanceof BABYLON.Plane) {
  101823. serializationGeometries.planes.push(geometry.serialize());
  101824. }
  101825. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  101826. serializationGeometries.torusKnots.push(geometry.serialize());
  101827. }
  101828. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  101829. throw new Error("Unknown primitive type");
  101830. }
  101831. else {
  101832. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  101833. }
  101834. serializedGeometries[geometry.id] = true;
  101835. };
  101836. var serializeMesh = function (mesh, serializationScene) {
  101837. var serializationObject = {};
  101838. // Geometry
  101839. var geometry = mesh._geometry;
  101840. if (geometry) {
  101841. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  101842. // 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
  101843. serializeGeometry(geometry, serializationScene.geometries);
  101844. }
  101845. }
  101846. // Custom
  101847. if (mesh.serialize) {
  101848. mesh.serialize(serializationObject);
  101849. }
  101850. return serializationObject;
  101851. };
  101852. var finalizeSingleMesh = function (mesh, serializationObject) {
  101853. //only works if the mesh is already loaded
  101854. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  101855. //serialize material
  101856. if (mesh.material) {
  101857. if (mesh.material instanceof BABYLON.MultiMaterial) {
  101858. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  101859. serializationObject.materials = serializationObject.materials || [];
  101860. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  101861. serializationObject.multiMaterials.push(mesh.material.serialize());
  101862. var _loop_1 = function (submaterial) {
  101863. if (submaterial) {
  101864. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  101865. serializationObject.materials.push(submaterial.serialize());
  101866. }
  101867. }
  101868. };
  101869. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  101870. var submaterial = _a[_i];
  101871. _loop_1(submaterial);
  101872. }
  101873. }
  101874. }
  101875. else {
  101876. serializationObject.materials = serializationObject.materials || [];
  101877. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  101878. serializationObject.materials.push(mesh.material.serialize());
  101879. }
  101880. }
  101881. }
  101882. //serialize geometry
  101883. var geometry = mesh._geometry;
  101884. if (geometry) {
  101885. if (!serializationObject.geometries) {
  101886. serializationObject.geometries = {};
  101887. serializationObject.geometries.boxes = [];
  101888. serializationObject.geometries.spheres = [];
  101889. serializationObject.geometries.cylinders = [];
  101890. serializationObject.geometries.toruses = [];
  101891. serializationObject.geometries.grounds = [];
  101892. serializationObject.geometries.planes = [];
  101893. serializationObject.geometries.torusKnots = [];
  101894. serializationObject.geometries.vertexData = [];
  101895. }
  101896. serializeGeometry(geometry, serializationObject.geometries);
  101897. }
  101898. // Skeletons
  101899. if (mesh.skeleton) {
  101900. serializationObject.skeletons = serializationObject.skeletons || [];
  101901. serializationObject.skeletons.push(mesh.skeleton.serialize());
  101902. }
  101903. //serialize the actual mesh
  101904. serializationObject.meshes = serializationObject.meshes || [];
  101905. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  101906. }
  101907. };
  101908. var SceneSerializer = /** @class */ (function () {
  101909. function SceneSerializer() {
  101910. }
  101911. SceneSerializer.ClearCache = function () {
  101912. serializedGeometries = [];
  101913. };
  101914. SceneSerializer.Serialize = function (scene) {
  101915. var serializationObject = {};
  101916. SceneSerializer.ClearCache();
  101917. // Scene
  101918. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  101919. serializationObject.autoClear = scene.autoClear;
  101920. serializationObject.clearColor = scene.clearColor.asArray();
  101921. serializationObject.ambientColor = scene.ambientColor.asArray();
  101922. serializationObject.gravity = scene.gravity.asArray();
  101923. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  101924. serializationObject.workerCollisions = scene.workerCollisions;
  101925. // Fog
  101926. if (scene.fogMode && scene.fogMode !== 0) {
  101927. serializationObject.fogMode = scene.fogMode;
  101928. serializationObject.fogColor = scene.fogColor.asArray();
  101929. serializationObject.fogStart = scene.fogStart;
  101930. serializationObject.fogEnd = scene.fogEnd;
  101931. serializationObject.fogDensity = scene.fogDensity;
  101932. }
  101933. //Physics
  101934. if (scene.isPhysicsEnabled()) {
  101935. var physicEngine = scene.getPhysicsEngine();
  101936. if (physicEngine) {
  101937. serializationObject.physicsEnabled = true;
  101938. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  101939. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  101940. }
  101941. }
  101942. // Metadata
  101943. if (scene.metadata) {
  101944. serializationObject.metadata = scene.metadata;
  101945. }
  101946. // Morph targets
  101947. serializationObject.morphTargetManagers = [];
  101948. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  101949. var abstractMesh = _a[_i];
  101950. var manager = abstractMesh.morphTargetManager;
  101951. if (manager) {
  101952. serializationObject.morphTargetManagers.push(manager.serialize());
  101953. }
  101954. }
  101955. // Lights
  101956. serializationObject.lights = [];
  101957. var index;
  101958. var light;
  101959. for (index = 0; index < scene.lights.length; index++) {
  101960. light = scene.lights[index];
  101961. if (!light.doNotSerialize) {
  101962. serializationObject.lights.push(light.serialize());
  101963. }
  101964. }
  101965. // Cameras
  101966. serializationObject.cameras = [];
  101967. for (index = 0; index < scene.cameras.length; index++) {
  101968. var camera = scene.cameras[index];
  101969. if (!camera.doNotSerialize) {
  101970. serializationObject.cameras.push(camera.serialize());
  101971. }
  101972. }
  101973. if (scene.activeCamera) {
  101974. serializationObject.activeCameraID = scene.activeCamera.id;
  101975. }
  101976. // Animations
  101977. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  101978. // Materials
  101979. serializationObject.materials = [];
  101980. serializationObject.multiMaterials = [];
  101981. var material;
  101982. for (index = 0; index < scene.materials.length; index++) {
  101983. material = scene.materials[index];
  101984. if (!material.doNotSerialize) {
  101985. serializationObject.materials.push(material.serialize());
  101986. }
  101987. }
  101988. // MultiMaterials
  101989. serializationObject.multiMaterials = [];
  101990. for (index = 0; index < scene.multiMaterials.length; index++) {
  101991. var multiMaterial = scene.multiMaterials[index];
  101992. serializationObject.multiMaterials.push(multiMaterial.serialize());
  101993. }
  101994. // Environment texture
  101995. if (scene.environmentTexture) {
  101996. serializationObject.environmentTexture = scene.environmentTexture.name;
  101997. }
  101998. // Skeletons
  101999. serializationObject.skeletons = [];
  102000. for (index = 0; index < scene.skeletons.length; index++) {
  102001. var skeleton = scene.skeletons[index];
  102002. if (!skeleton.doNotSerialize) {
  102003. serializationObject.skeletons.push(skeleton.serialize());
  102004. }
  102005. }
  102006. // Transform nodes
  102007. serializationObject.transformNodes = [];
  102008. for (index = 0; index < scene.transformNodes.length; index++) {
  102009. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  102010. }
  102011. // Geometries
  102012. serializationObject.geometries = {};
  102013. serializationObject.geometries.boxes = [];
  102014. serializationObject.geometries.spheres = [];
  102015. serializationObject.geometries.cylinders = [];
  102016. serializationObject.geometries.toruses = [];
  102017. serializationObject.geometries.grounds = [];
  102018. serializationObject.geometries.planes = [];
  102019. serializationObject.geometries.torusKnots = [];
  102020. serializationObject.geometries.vertexData = [];
  102021. serializedGeometries = [];
  102022. var geometries = scene.getGeometries();
  102023. for (index = 0; index < geometries.length; index++) {
  102024. var geometry = geometries[index];
  102025. if (geometry.isReady()) {
  102026. serializeGeometry(geometry, serializationObject.geometries);
  102027. }
  102028. }
  102029. // Meshes
  102030. serializationObject.meshes = [];
  102031. for (index = 0; index < scene.meshes.length; index++) {
  102032. var abstractMesh = scene.meshes[index];
  102033. if (abstractMesh instanceof BABYLON.Mesh) {
  102034. var mesh = abstractMesh;
  102035. if (!mesh.doNotSerialize) {
  102036. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102037. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102038. }
  102039. }
  102040. }
  102041. }
  102042. // Particles Systems
  102043. serializationObject.particleSystems = [];
  102044. for (index = 0; index < scene.particleSystems.length; index++) {
  102045. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  102046. }
  102047. // Shadows
  102048. serializationObject.shadowGenerators = [];
  102049. for (index = 0; index < scene.lights.length; index++) {
  102050. light = scene.lights[index];
  102051. var shadowGenerator = light.getShadowGenerator();
  102052. if (shadowGenerator) {
  102053. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  102054. }
  102055. }
  102056. // Action Manager
  102057. if (scene.actionManager) {
  102058. serializationObject.actions = scene.actionManager.serialize("scene");
  102059. }
  102060. // Audio
  102061. serializationObject.sounds = [];
  102062. for (index = 0; index < scene.soundTracks.length; index++) {
  102063. var soundtrack = scene.soundTracks[index];
  102064. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  102065. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  102066. }
  102067. }
  102068. // Components
  102069. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  102070. var component = _c[_b];
  102071. component.serialize(serializationObject);
  102072. }
  102073. return serializationObject;
  102074. };
  102075. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  102076. if (withParents === void 0) { withParents = false; }
  102077. if (withChildren === void 0) { withChildren = false; }
  102078. var serializationObject = {};
  102079. SceneSerializer.ClearCache();
  102080. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  102081. if (withParents || withChildren) {
  102082. //deliberate for loop! not for each, appended should be processed as well.
  102083. for (var i = 0; i < toSerialize.length; ++i) {
  102084. if (withChildren) {
  102085. toSerialize[i].getDescendants().forEach(function (node) {
  102086. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  102087. toSerialize.push(node);
  102088. }
  102089. });
  102090. }
  102091. //make sure the array doesn't contain the object already
  102092. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  102093. toSerialize.push(toSerialize[i].parent);
  102094. }
  102095. }
  102096. }
  102097. toSerialize.forEach(function (mesh) {
  102098. finalizeSingleMesh(mesh, serializationObject);
  102099. });
  102100. return serializationObject;
  102101. };
  102102. return SceneSerializer;
  102103. }());
  102104. BABYLON.SceneSerializer = SceneSerializer;
  102105. })(BABYLON || (BABYLON = {}));
  102106. //# sourceMappingURL=babylon.sceneSerializer.js.map
  102107. var BABYLON;
  102108. (function (BABYLON) {
  102109. /**
  102110. * Class used to generate realtime reflection / refraction cube textures
  102111. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  102112. */
  102113. var ReflectionProbe = /** @class */ (function () {
  102114. /**
  102115. * Creates a new reflection probe
  102116. * @param name defines the name of the probe
  102117. * @param size defines the texture resolution (for each face)
  102118. * @param scene defines the hosting scene
  102119. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  102120. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  102121. */
  102122. function ReflectionProbe(
  102123. /** defines the name of the probe */
  102124. name, size, scene, generateMipMaps, useFloat) {
  102125. if (generateMipMaps === void 0) { generateMipMaps = true; }
  102126. if (useFloat === void 0) { useFloat = false; }
  102127. var _this = this;
  102128. this.name = name;
  102129. this._viewMatrix = BABYLON.Matrix.Identity();
  102130. this._target = BABYLON.Vector3.Zero();
  102131. this._add = BABYLON.Vector3.Zero();
  102132. this._invertYAxis = false;
  102133. /** Gets or sets probe position (center of the cube map) */
  102134. this.position = BABYLON.Vector3.Zero();
  102135. this._scene = scene;
  102136. this._scene.reflectionProbes.push(this);
  102137. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  102138. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  102139. switch (faceIndex) {
  102140. case 0:
  102141. _this._add.copyFromFloats(1, 0, 0);
  102142. break;
  102143. case 1:
  102144. _this._add.copyFromFloats(-1, 0, 0);
  102145. break;
  102146. case 2:
  102147. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  102148. break;
  102149. case 3:
  102150. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  102151. break;
  102152. case 4:
  102153. _this._add.copyFromFloats(0, 0, 1);
  102154. break;
  102155. case 5:
  102156. _this._add.copyFromFloats(0, 0, -1);
  102157. break;
  102158. }
  102159. if (_this._attachedMesh) {
  102160. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  102161. }
  102162. _this.position.addToRef(_this._add, _this._target);
  102163. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  102164. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  102165. scene._forcedViewPosition = _this.position;
  102166. });
  102167. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  102168. scene._forcedViewPosition = null;
  102169. scene.updateTransformMatrix(true);
  102170. });
  102171. if (scene.activeCamera) {
  102172. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  102173. }
  102174. }
  102175. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  102176. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  102177. get: function () {
  102178. return this._renderTargetTexture.samples;
  102179. },
  102180. set: function (value) {
  102181. this._renderTargetTexture.samples = value;
  102182. },
  102183. enumerable: true,
  102184. configurable: true
  102185. });
  102186. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  102187. /** Gets or sets the refresh rate to use (on every frame by default) */
  102188. get: function () {
  102189. return this._renderTargetTexture.refreshRate;
  102190. },
  102191. set: function (value) {
  102192. this._renderTargetTexture.refreshRate = value;
  102193. },
  102194. enumerable: true,
  102195. configurable: true
  102196. });
  102197. /**
  102198. * Gets the hosting scene
  102199. * @returns a Scene
  102200. */
  102201. ReflectionProbe.prototype.getScene = function () {
  102202. return this._scene;
  102203. };
  102204. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  102205. /** Gets the internal CubeTexture used to render to */
  102206. get: function () {
  102207. return this._renderTargetTexture;
  102208. },
  102209. enumerable: true,
  102210. configurable: true
  102211. });
  102212. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  102213. /** Gets the list of meshes to render */
  102214. get: function () {
  102215. return this._renderTargetTexture.renderList;
  102216. },
  102217. enumerable: true,
  102218. configurable: true
  102219. });
  102220. /**
  102221. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  102222. * @param mesh defines the mesh to attach to
  102223. */
  102224. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  102225. this._attachedMesh = mesh;
  102226. };
  102227. /**
  102228. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  102229. * @param renderingGroupId The rendering group id corresponding to its index
  102230. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  102231. */
  102232. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  102233. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  102234. };
  102235. /**
  102236. * Clean all associated resources
  102237. */
  102238. ReflectionProbe.prototype.dispose = function () {
  102239. var index = this._scene.reflectionProbes.indexOf(this);
  102240. if (index !== -1) {
  102241. // Remove from the scene if found
  102242. this._scene.reflectionProbes.splice(index, 1);
  102243. }
  102244. if (this._renderTargetTexture) {
  102245. this._renderTargetTexture.dispose();
  102246. this._renderTargetTexture = null;
  102247. }
  102248. };
  102249. return ReflectionProbe;
  102250. }());
  102251. BABYLON.ReflectionProbe = ReflectionProbe;
  102252. })(BABYLON || (BABYLON = {}));
  102253. //# sourceMappingURL=babylon.reflectionProbe.js.map
  102254. var BABYLON;
  102255. (function (BABYLON) {
  102256. /**
  102257. * Defines the layer scene component responsible to manage any layers
  102258. * in a given scene.
  102259. */
  102260. var LayerSceneComponent = /** @class */ (function () {
  102261. /**
  102262. * Creates a new instance of the component for the given scene
  102263. * @param scene Defines the scene to register the component in
  102264. */
  102265. function LayerSceneComponent(scene) {
  102266. /**
  102267. * The component name helpfull to identify the component in the list of scene components.
  102268. */
  102269. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  102270. this.scene = scene;
  102271. this._engine = scene.getEngine();
  102272. scene.layers = new Array();
  102273. }
  102274. /**
  102275. * Registers the component in a given scene
  102276. */
  102277. LayerSceneComponent.prototype.register = function () {
  102278. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  102279. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  102280. };
  102281. /**
  102282. * Rebuilds the elements related to this component in case of
  102283. * context lost for instance.
  102284. */
  102285. LayerSceneComponent.prototype.rebuild = function () {
  102286. var layers = this.scene.layers;
  102287. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102288. var layer = layers_1[_i];
  102289. layer._rebuild();
  102290. }
  102291. };
  102292. /**
  102293. * Disposes the component and the associated ressources.
  102294. */
  102295. LayerSceneComponent.prototype.dispose = function () {
  102296. var layers = this.scene.layers;
  102297. while (layers.length) {
  102298. layers[0].dispose();
  102299. }
  102300. };
  102301. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  102302. var layers = this.scene.layers;
  102303. if (layers.length) {
  102304. this._engine.setDepthBuffer(false);
  102305. var cameraLayerMask = camera.layerMask;
  102306. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102307. var layer = layers_2[_i];
  102308. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  102309. layer.render();
  102310. }
  102311. }
  102312. this._engine.setDepthBuffer(true);
  102313. }
  102314. };
  102315. LayerSceneComponent.prototype._drawBackground = function (camera) {
  102316. this._draw(camera, true);
  102317. };
  102318. LayerSceneComponent.prototype._drawForeground = function (camera) {
  102319. this._draw(camera, false);
  102320. };
  102321. return LayerSceneComponent;
  102322. }());
  102323. BABYLON.LayerSceneComponent = LayerSceneComponent;
  102324. })(BABYLON || (BABYLON = {}));
  102325. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  102326. var BABYLON;
  102327. (function (BABYLON) {
  102328. var Layer = /** @class */ (function () {
  102329. function Layer(name, imgUrl, scene, isBackground, color) {
  102330. this.name = name;
  102331. this.scale = new BABYLON.Vector2(1, 1);
  102332. this.offset = new BABYLON.Vector2(0, 0);
  102333. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  102334. this.layerMask = 0x0FFFFFFF;
  102335. this._vertexBuffers = {};
  102336. // Events
  102337. /**
  102338. * An event triggered when the layer is disposed.
  102339. */
  102340. this.onDisposeObservable = new BABYLON.Observable();
  102341. /**
  102342. * An event triggered before rendering the scene
  102343. */
  102344. this.onBeforeRenderObservable = new BABYLON.Observable();
  102345. /**
  102346. * An event triggered after rendering the scene
  102347. */
  102348. this.onAfterRenderObservable = new BABYLON.Observable();
  102349. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  102350. this.isBackground = isBackground === undefined ? true : isBackground;
  102351. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  102352. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  102353. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  102354. if (!layerComponent) {
  102355. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  102356. this._scene._addComponent(layerComponent);
  102357. }
  102358. this._scene.layers.push(this);
  102359. var engine = this._scene.getEngine();
  102360. // VBO
  102361. var vertices = [];
  102362. vertices.push(1, 1);
  102363. vertices.push(-1, 1);
  102364. vertices.push(-1, -1);
  102365. vertices.push(1, -1);
  102366. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102367. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102368. this._createIndexBuffer();
  102369. // Effects
  102370. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  102371. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  102372. }
  102373. Object.defineProperty(Layer.prototype, "onDispose", {
  102374. set: function (callback) {
  102375. if (this._onDisposeObserver) {
  102376. this.onDisposeObservable.remove(this._onDisposeObserver);
  102377. }
  102378. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102379. },
  102380. enumerable: true,
  102381. configurable: true
  102382. });
  102383. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  102384. set: function (callback) {
  102385. if (this._onBeforeRenderObserver) {
  102386. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  102387. }
  102388. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  102389. },
  102390. enumerable: true,
  102391. configurable: true
  102392. });
  102393. Object.defineProperty(Layer.prototype, "onAfterRender", {
  102394. set: function (callback) {
  102395. if (this._onAfterRenderObserver) {
  102396. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102397. }
  102398. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  102399. },
  102400. enumerable: true,
  102401. configurable: true
  102402. });
  102403. Layer.prototype._createIndexBuffer = function () {
  102404. var engine = this._scene.getEngine();
  102405. // Indices
  102406. var indices = [];
  102407. indices.push(0);
  102408. indices.push(1);
  102409. indices.push(2);
  102410. indices.push(0);
  102411. indices.push(2);
  102412. indices.push(3);
  102413. this._indexBuffer = engine.createIndexBuffer(indices);
  102414. };
  102415. /** @hidden */
  102416. Layer.prototype._rebuild = function () {
  102417. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102418. if (vb) {
  102419. vb._rebuild();
  102420. }
  102421. this._createIndexBuffer();
  102422. };
  102423. Layer.prototype.render = function () {
  102424. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  102425. // Check
  102426. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  102427. return;
  102428. var engine = this._scene.getEngine();
  102429. this.onBeforeRenderObservable.notifyObservers(this);
  102430. // Render
  102431. engine.enableEffect(currentEffect);
  102432. engine.setState(false);
  102433. // Texture
  102434. currentEffect.setTexture("textureSampler", this.texture);
  102435. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  102436. // Color
  102437. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  102438. // Scale / offset
  102439. currentEffect.setVector2("offset", this.offset);
  102440. currentEffect.setVector2("scale", this.scale);
  102441. // VBOs
  102442. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102443. // Draw order
  102444. if (!this.alphaTest) {
  102445. engine.setAlphaMode(this.alphaBlendingMode);
  102446. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102447. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  102448. }
  102449. else {
  102450. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102451. }
  102452. this.onAfterRenderObservable.notifyObservers(this);
  102453. };
  102454. Layer.prototype.dispose = function () {
  102455. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102456. if (vertexBuffer) {
  102457. vertexBuffer.dispose();
  102458. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102459. }
  102460. if (this._indexBuffer) {
  102461. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102462. this._indexBuffer = null;
  102463. }
  102464. if (this.texture) {
  102465. this.texture.dispose();
  102466. this.texture = null;
  102467. }
  102468. // Remove from scene
  102469. var index = this._scene.layers.indexOf(this);
  102470. this._scene.layers.splice(index, 1);
  102471. // Callback
  102472. this.onDisposeObservable.notifyObservers(this);
  102473. this.onDisposeObservable.clear();
  102474. this.onAfterRenderObservable.clear();
  102475. this.onBeforeRenderObservable.clear();
  102476. };
  102477. return Layer;
  102478. }());
  102479. BABYLON.Layer = Layer;
  102480. })(BABYLON || (BABYLON = {}));
  102481. //# sourceMappingURL=babylon.layer.js.map
  102482. var BABYLON;
  102483. (function (BABYLON) {
  102484. var TextureTools = /** @class */ (function () {
  102485. function TextureTools() {
  102486. }
  102487. /**
  102488. * Uses the GPU to create a copy texture rescaled at a given size
  102489. * @param texture Texture to copy from
  102490. * @param width Desired width
  102491. * @param height Desired height
  102492. * @return Generated texture
  102493. */
  102494. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  102495. if (useBilinearMode === void 0) { useBilinearMode = true; }
  102496. var scene = texture.getScene();
  102497. var engine = scene.getEngine();
  102498. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  102499. rtt.wrapU = texture.wrapU;
  102500. rtt.wrapV = texture.wrapV;
  102501. rtt.uOffset = texture.uOffset;
  102502. rtt.vOffset = texture.vOffset;
  102503. rtt.uScale = texture.uScale;
  102504. rtt.vScale = texture.vScale;
  102505. rtt.uAng = texture.uAng;
  102506. rtt.vAng = texture.vAng;
  102507. rtt.wAng = texture.wAng;
  102508. rtt.coordinatesIndex = texture.coordinatesIndex;
  102509. rtt.level = texture.level;
  102510. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  102511. rtt._texture.isReady = false;
  102512. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102513. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102514. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102515. passPostProcess.getEffect().executeWhenCompiled(function () {
  102516. passPostProcess.onApply = function (effect) {
  102517. effect.setTexture("textureSampler", texture);
  102518. };
  102519. var internalTexture = rtt.getInternalTexture();
  102520. if (internalTexture) {
  102521. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  102522. engine.unBindFramebuffer(internalTexture);
  102523. rtt.disposeFramebufferObjects();
  102524. passPostProcess.dispose();
  102525. internalTexture.isReady = true;
  102526. }
  102527. });
  102528. return rtt;
  102529. };
  102530. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  102531. if (!scene._environmentBRDFTexture) {
  102532. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102533. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102534. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102535. scene._environmentBRDFTexture = texture;
  102536. }
  102537. return scene._environmentBRDFTexture;
  102538. };
  102539. 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=";
  102540. return TextureTools;
  102541. }());
  102542. BABYLON.TextureTools = TextureTools;
  102543. })(BABYLON || (BABYLON = {}));
  102544. //# sourceMappingURL=babylon.textureTools.js.map
  102545. var BABYLON;
  102546. (function (BABYLON) {
  102547. var FramingBehavior = /** @class */ (function () {
  102548. function FramingBehavior() {
  102549. this._mode = FramingBehavior.FitFrustumSidesMode;
  102550. this._radiusScale = 1.0;
  102551. this._positionScale = 0.5;
  102552. this._defaultElevation = 0.3;
  102553. this._elevationReturnTime = 1500;
  102554. this._elevationReturnWaitTime = 1000;
  102555. this._zoomStopsAnimation = false;
  102556. this._framingTime = 1500;
  102557. this._isPointerDown = false;
  102558. this._lastInteractionTime = -Infinity;
  102559. // Framing control
  102560. this._animatables = new Array();
  102561. this._betaIsAnimating = false;
  102562. }
  102563. Object.defineProperty(FramingBehavior.prototype, "name", {
  102564. get: function () {
  102565. return "Framing";
  102566. },
  102567. enumerable: true,
  102568. configurable: true
  102569. });
  102570. Object.defineProperty(FramingBehavior.prototype, "mode", {
  102571. /**
  102572. * Gets current mode used by the behavior.
  102573. */
  102574. get: function () {
  102575. return this._mode;
  102576. },
  102577. /**
  102578. * Sets the current mode used by the behavior
  102579. */
  102580. set: function (mode) {
  102581. this._mode = mode;
  102582. },
  102583. enumerable: true,
  102584. configurable: true
  102585. });
  102586. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  102587. /**
  102588. * Gets the scale applied to the radius
  102589. */
  102590. get: function () {
  102591. return this._radiusScale;
  102592. },
  102593. /**
  102594. * Sets the scale applied to the radius (1 by default)
  102595. */
  102596. set: function (radius) {
  102597. this._radiusScale = radius;
  102598. },
  102599. enumerable: true,
  102600. configurable: true
  102601. });
  102602. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  102603. /**
  102604. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  102605. */
  102606. get: function () {
  102607. return this._positionScale;
  102608. },
  102609. /**
  102610. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  102611. */
  102612. set: function (scale) {
  102613. this._positionScale = scale;
  102614. },
  102615. enumerable: true,
  102616. configurable: true
  102617. });
  102618. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  102619. /**
  102620. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  102621. * behaviour is triggered, in radians.
  102622. */
  102623. get: function () {
  102624. return this._defaultElevation;
  102625. },
  102626. /**
  102627. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  102628. * behaviour is triggered, in radians.
  102629. */
  102630. set: function (elevation) {
  102631. this._defaultElevation = elevation;
  102632. },
  102633. enumerable: true,
  102634. configurable: true
  102635. });
  102636. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  102637. /**
  102638. * Gets the time (in milliseconds) taken to return to the default beta position.
  102639. * Negative value indicates camera should not return to default.
  102640. */
  102641. get: function () {
  102642. return this._elevationReturnTime;
  102643. },
  102644. /**
  102645. * Sets the time (in milliseconds) taken to return to the default beta position.
  102646. * Negative value indicates camera should not return to default.
  102647. */
  102648. set: function (speed) {
  102649. this._elevationReturnTime = speed;
  102650. },
  102651. enumerable: true,
  102652. configurable: true
  102653. });
  102654. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  102655. /**
  102656. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  102657. */
  102658. get: function () {
  102659. return this._elevationReturnWaitTime;
  102660. },
  102661. /**
  102662. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  102663. */
  102664. set: function (time) {
  102665. this._elevationReturnWaitTime = time;
  102666. },
  102667. enumerable: true,
  102668. configurable: true
  102669. });
  102670. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  102671. /**
  102672. * Gets the flag that indicates if user zooming should stop animation.
  102673. */
  102674. get: function () {
  102675. return this._zoomStopsAnimation;
  102676. },
  102677. /**
  102678. * Sets the flag that indicates if user zooming should stop animation.
  102679. */
  102680. set: function (flag) {
  102681. this._zoomStopsAnimation = flag;
  102682. },
  102683. enumerable: true,
  102684. configurable: true
  102685. });
  102686. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  102687. /**
  102688. * Gets the transition time when framing the mesh, in milliseconds
  102689. */
  102690. get: function () {
  102691. return this._framingTime;
  102692. },
  102693. /**
  102694. * Sets the transition time when framing the mesh, in milliseconds
  102695. */
  102696. set: function (time) {
  102697. this._framingTime = time;
  102698. },
  102699. enumerable: true,
  102700. configurable: true
  102701. });
  102702. FramingBehavior.prototype.init = function () {
  102703. // Do notihng
  102704. };
  102705. FramingBehavior.prototype.attach = function (camera) {
  102706. var _this = this;
  102707. this._attachedCamera = camera;
  102708. var scene = this._attachedCamera.getScene();
  102709. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  102710. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  102711. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  102712. _this._isPointerDown = true;
  102713. return;
  102714. }
  102715. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  102716. _this._isPointerDown = false;
  102717. }
  102718. });
  102719. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  102720. if (mesh) {
  102721. _this.zoomOnMesh(mesh);
  102722. }
  102723. });
  102724. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  102725. // Stop the animation if there is user interaction and the animation should stop for this interaction
  102726. _this._applyUserInteraction();
  102727. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  102728. // back to the default position after a given timeout
  102729. _this._maintainCameraAboveGround();
  102730. });
  102731. };
  102732. FramingBehavior.prototype.detach = function () {
  102733. if (!this._attachedCamera) {
  102734. return;
  102735. }
  102736. var scene = this._attachedCamera.getScene();
  102737. if (this._onPrePointerObservableObserver) {
  102738. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  102739. }
  102740. if (this._onAfterCheckInputsObserver) {
  102741. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  102742. }
  102743. if (this._onMeshTargetChangedObserver) {
  102744. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  102745. }
  102746. this._attachedCamera = null;
  102747. };
  102748. /**
  102749. * Targets the given mesh and updates zoom level accordingly.
  102750. * @param mesh The mesh to target.
  102751. * @param radius Optional. If a cached radius position already exists, overrides default.
  102752. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102753. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102754. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102755. */
  102756. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  102757. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102758. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102759. mesh.computeWorldMatrix(true);
  102760. var boundingBox = mesh.getBoundingInfo().boundingBox;
  102761. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  102762. };
  102763. /**
  102764. * Targets the given mesh with its children and updates zoom level accordingly.
  102765. * @param mesh The mesh to target.
  102766. * @param radius Optional. If a cached radius position already exists, overrides default.
  102767. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102768. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102769. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102770. */
  102771. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  102772. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102773. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102774. mesh.computeWorldMatrix(true);
  102775. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  102776. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  102777. };
  102778. /**
  102779. * Targets the given meshes with their children and updates zoom level accordingly.
  102780. * @param meshes The mesh to target.
  102781. * @param radius Optional. If a cached radius position already exists, overrides default.
  102782. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102783. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102784. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102785. */
  102786. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  102787. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102788. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102789. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  102790. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  102791. for (var i = 0; i < meshes.length; i++) {
  102792. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  102793. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  102794. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  102795. }
  102796. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  102797. };
  102798. /**
  102799. * Targets the given mesh and updates zoom level accordingly.
  102800. * @param mesh The mesh to target.
  102801. * @param radius Optional. If a cached radius position already exists, overrides default.
  102802. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102803. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102804. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102805. */
  102806. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  102807. var _this = this;
  102808. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102809. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102810. var zoomTarget;
  102811. if (!this._attachedCamera) {
  102812. return;
  102813. }
  102814. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  102815. var bottom = minimumWorld.y;
  102816. var top = maximumWorld.y;
  102817. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  102818. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  102819. if (focusOnOriginXZ) {
  102820. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  102821. }
  102822. else {
  102823. var centerWorld = minimumWorld.add(radiusWorld);
  102824. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  102825. }
  102826. if (!this._vectorTransition) {
  102827. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  102828. }
  102829. this._betaIsAnimating = true;
  102830. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  102831. if (animatable) {
  102832. this._animatables.push(animatable);
  102833. }
  102834. // sets the radius and lower radius bounds
  102835. // Small delta ensures camera is not always at lower zoom limit.
  102836. var radius = 0;
  102837. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  102838. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  102839. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  102840. radius = position;
  102841. }
  102842. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  102843. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  102844. if (this._attachedCamera.lowerRadiusLimit === null) {
  102845. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  102846. }
  102847. }
  102848. // Set sensibilities
  102849. var extend = maximumWorld.subtract(minimumWorld).length();
  102850. this._attachedCamera.panningSensibility = 5000 / extend;
  102851. this._attachedCamera.wheelPrecision = 100 / radius;
  102852. // transition to new radius
  102853. if (!this._radiusTransition) {
  102854. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  102855. }
  102856. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  102857. _this.stopAllAnimations();
  102858. if (onAnimationEnd) {
  102859. onAnimationEnd();
  102860. }
  102861. if (_this._attachedCamera) {
  102862. _this._attachedCamera.storeState();
  102863. }
  102864. });
  102865. if (animatable) {
  102866. this._animatables.push(animatable);
  102867. }
  102868. };
  102869. /**
  102870. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  102871. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  102872. * frustum width.
  102873. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  102874. * to fully enclose the mesh in the viewing frustum.
  102875. */
  102876. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  102877. var size = maximumWorld.subtract(minimumWorld);
  102878. var boxVectorGlobalDiagonal = size.length();
  102879. var frustumSlope = this._getFrustumSlope();
  102880. // Formula for setting distance
  102881. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  102882. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  102883. // Horizon distance
  102884. var radius = radiusWithoutFraming * this._radiusScale;
  102885. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  102886. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  102887. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  102888. var camera = this._attachedCamera;
  102889. if (!camera) {
  102890. return 0;
  102891. }
  102892. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  102893. // Don't exceed the requested limit
  102894. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  102895. }
  102896. // Don't exceed the upper radius limit
  102897. if (camera.upperRadiusLimit) {
  102898. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  102899. }
  102900. return distance;
  102901. };
  102902. /**
  102903. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  102904. * is automatically returned to its default position (expected to be above ground plane).
  102905. */
  102906. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  102907. var _this = this;
  102908. if (this._elevationReturnTime < 0) {
  102909. return;
  102910. }
  102911. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  102912. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  102913. var limitBeta = Math.PI * 0.5;
  102914. // Bring the camera back up if below the ground plane
  102915. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  102916. this._betaIsAnimating = true;
  102917. //Transition to new position
  102918. this.stopAllAnimations();
  102919. if (!this._betaTransition) {
  102920. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  102921. }
  102922. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  102923. _this._clearAnimationLocks();
  102924. _this.stopAllAnimations();
  102925. });
  102926. if (animatabe) {
  102927. this._animatables.push(animatabe);
  102928. }
  102929. }
  102930. };
  102931. /**
  102932. * Returns the frustum slope based on the canvas ratio and camera FOV
  102933. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  102934. */
  102935. FramingBehavior.prototype._getFrustumSlope = function () {
  102936. // Calculate the viewport ratio
  102937. // Aspect Ratio is Height/Width.
  102938. var camera = this._attachedCamera;
  102939. if (!camera) {
  102940. return BABYLON.Vector2.Zero();
  102941. }
  102942. var engine = camera.getScene().getEngine();
  102943. var aspectRatio = engine.getAspectRatio(camera);
  102944. // Camera FOV is the vertical field of view (top-bottom) in radians.
  102945. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  102946. var frustumSlopeY = Math.tan(camera.fov / 2);
  102947. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  102948. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  102949. // along the forward vector.
  102950. var frustumSlopeX = frustumSlopeY * aspectRatio;
  102951. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  102952. };
  102953. /**
  102954. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  102955. */
  102956. FramingBehavior.prototype._clearAnimationLocks = function () {
  102957. this._betaIsAnimating = false;
  102958. };
  102959. /**
  102960. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  102961. */
  102962. FramingBehavior.prototype._applyUserInteraction = function () {
  102963. if (this.isUserIsMoving) {
  102964. this._lastInteractionTime = BABYLON.Tools.Now;
  102965. this.stopAllAnimations();
  102966. this._clearAnimationLocks();
  102967. }
  102968. };
  102969. /**
  102970. * Stops and removes all animations that have been applied to the camera
  102971. */
  102972. FramingBehavior.prototype.stopAllAnimations = function () {
  102973. if (this._attachedCamera) {
  102974. this._attachedCamera.animations = [];
  102975. }
  102976. while (this._animatables.length) {
  102977. if (this._animatables[0]) {
  102978. this._animatables[0].onAnimationEnd = null;
  102979. this._animatables[0].stop();
  102980. }
  102981. this._animatables.shift();
  102982. }
  102983. };
  102984. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  102985. /**
  102986. * Gets a value indicating if the user is moving the camera
  102987. */
  102988. get: function () {
  102989. if (!this._attachedCamera) {
  102990. return false;
  102991. }
  102992. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  102993. this._attachedCamera.inertialBetaOffset !== 0 ||
  102994. this._attachedCamera.inertialRadiusOffset !== 0 ||
  102995. this._attachedCamera.inertialPanningX !== 0 ||
  102996. this._attachedCamera.inertialPanningY !== 0 ||
  102997. this._isPointerDown;
  102998. },
  102999. enumerable: true,
  103000. configurable: true
  103001. });
  103002. /**
  103003. * The easing function used by animations
  103004. */
  103005. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  103006. /**
  103007. * The easing mode used by animations
  103008. */
  103009. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  103010. // Statics
  103011. /**
  103012. * The camera can move all the way towards the mesh.
  103013. */
  103014. FramingBehavior.IgnoreBoundsSizeMode = 0;
  103015. /**
  103016. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  103017. */
  103018. FramingBehavior.FitFrustumSidesMode = 1;
  103019. return FramingBehavior;
  103020. }());
  103021. BABYLON.FramingBehavior = FramingBehavior;
  103022. })(BABYLON || (BABYLON = {}));
  103023. //# sourceMappingURL=babylon.framingBehavior.js.map
  103024. var BABYLON;
  103025. (function (BABYLON) {
  103026. /**
  103027. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  103028. */
  103029. var BouncingBehavior = /** @class */ (function () {
  103030. function BouncingBehavior() {
  103031. /**
  103032. * The duration of the animation, in milliseconds
  103033. */
  103034. this.transitionDuration = 450;
  103035. /**
  103036. * Length of the distance animated by the transition when lower radius is reached
  103037. */
  103038. this.lowerRadiusTransitionRange = 2;
  103039. /**
  103040. * Length of the distance animated by the transition when upper radius is reached
  103041. */
  103042. this.upperRadiusTransitionRange = -2;
  103043. this._autoTransitionRange = false;
  103044. // Animations
  103045. this._radiusIsAnimating = false;
  103046. this._radiusBounceTransition = null;
  103047. this._animatables = new Array();
  103048. }
  103049. Object.defineProperty(BouncingBehavior.prototype, "name", {
  103050. get: function () {
  103051. return "Bouncing";
  103052. },
  103053. enumerable: true,
  103054. configurable: true
  103055. });
  103056. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  103057. /**
  103058. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103059. */
  103060. get: function () {
  103061. return this._autoTransitionRange;
  103062. },
  103063. /**
  103064. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103065. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  103066. */
  103067. set: function (value) {
  103068. var _this = this;
  103069. if (this._autoTransitionRange === value) {
  103070. return;
  103071. }
  103072. this._autoTransitionRange = value;
  103073. var camera = this._attachedCamera;
  103074. if (!camera) {
  103075. return;
  103076. }
  103077. if (value) {
  103078. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103079. if (!mesh) {
  103080. return;
  103081. }
  103082. mesh.computeWorldMatrix(true);
  103083. var diagonal = mesh.getBoundingInfo().diagonalLength;
  103084. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  103085. _this.upperRadiusTransitionRange = diagonal * 0.05;
  103086. });
  103087. }
  103088. else if (this._onMeshTargetChangedObserver) {
  103089. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103090. }
  103091. },
  103092. enumerable: true,
  103093. configurable: true
  103094. });
  103095. BouncingBehavior.prototype.init = function () {
  103096. // Do notihng
  103097. };
  103098. BouncingBehavior.prototype.attach = function (camera) {
  103099. var _this = this;
  103100. this._attachedCamera = camera;
  103101. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103102. if (!_this._attachedCamera) {
  103103. return;
  103104. }
  103105. // Add the bounce animation to the lower radius limit
  103106. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  103107. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  103108. }
  103109. // Add the bounce animation to the upper radius limit
  103110. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  103111. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  103112. }
  103113. });
  103114. };
  103115. BouncingBehavior.prototype.detach = function () {
  103116. if (!this._attachedCamera) {
  103117. return;
  103118. }
  103119. if (this._onAfterCheckInputsObserver) {
  103120. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103121. }
  103122. if (this._onMeshTargetChangedObserver) {
  103123. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103124. }
  103125. this._attachedCamera = null;
  103126. };
  103127. /**
  103128. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  103129. * @param radiusLimit The limit to check against.
  103130. * @return Bool to indicate if at limit.
  103131. */
  103132. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  103133. if (!this._attachedCamera) {
  103134. return false;
  103135. }
  103136. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  103137. return true;
  103138. }
  103139. return false;
  103140. };
  103141. /**
  103142. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  103143. * @param radiusDelta The delta by which to animate to. Can be negative.
  103144. */
  103145. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  103146. var _this = this;
  103147. if (!this._attachedCamera) {
  103148. return;
  103149. }
  103150. if (!this._radiusBounceTransition) {
  103151. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  103152. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  103153. }
  103154. // Prevent zoom until bounce has completed
  103155. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  103156. this._attachedCamera.wheelPrecision = Infinity;
  103157. this._attachedCamera.inertialRadiusOffset = 0;
  103158. // Animate to the radius limit
  103159. this.stopAllAnimations();
  103160. this._radiusIsAnimating = true;
  103161. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  103162. if (animatable) {
  103163. this._animatables.push(animatable);
  103164. }
  103165. };
  103166. /**
  103167. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  103168. */
  103169. BouncingBehavior.prototype._clearAnimationLocks = function () {
  103170. this._radiusIsAnimating = false;
  103171. if (this._attachedCamera) {
  103172. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  103173. }
  103174. };
  103175. /**
  103176. * Stops and removes all animations that have been applied to the camera
  103177. */
  103178. BouncingBehavior.prototype.stopAllAnimations = function () {
  103179. if (this._attachedCamera) {
  103180. this._attachedCamera.animations = [];
  103181. }
  103182. while (this._animatables.length) {
  103183. this._animatables[0].onAnimationEnd = null;
  103184. this._animatables[0].stop();
  103185. this._animatables.shift();
  103186. }
  103187. };
  103188. /**
  103189. * The easing function used by animations
  103190. */
  103191. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  103192. /**
  103193. * The easing mode used by animations
  103194. */
  103195. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  103196. return BouncingBehavior;
  103197. }());
  103198. BABYLON.BouncingBehavior = BouncingBehavior;
  103199. })(BABYLON || (BABYLON = {}));
  103200. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  103201. var BABYLON;
  103202. (function (BABYLON) {
  103203. var AutoRotationBehavior = /** @class */ (function () {
  103204. function AutoRotationBehavior() {
  103205. this._zoomStopsAnimation = false;
  103206. this._idleRotationSpeed = 0.05;
  103207. this._idleRotationWaitTime = 2000;
  103208. this._idleRotationSpinupTime = 2000;
  103209. this._isPointerDown = false;
  103210. this._lastFrameTime = null;
  103211. this._lastInteractionTime = -Infinity;
  103212. this._cameraRotationSpeed = 0;
  103213. this._lastFrameRadius = 0;
  103214. }
  103215. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  103216. get: function () {
  103217. return "AutoRotation";
  103218. },
  103219. enumerable: true,
  103220. configurable: true
  103221. });
  103222. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  103223. /**
  103224. * Gets the flag that indicates if user zooming should stop animation.
  103225. */
  103226. get: function () {
  103227. return this._zoomStopsAnimation;
  103228. },
  103229. /**
  103230. * Sets the flag that indicates if user zooming should stop animation.
  103231. */
  103232. set: function (flag) {
  103233. this._zoomStopsAnimation = flag;
  103234. },
  103235. enumerable: true,
  103236. configurable: true
  103237. });
  103238. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  103239. /**
  103240. * Gets the default speed at which the camera rotates around the model.
  103241. */
  103242. get: function () {
  103243. return this._idleRotationSpeed;
  103244. },
  103245. /**
  103246. * Sets the default speed at which the camera rotates around the model.
  103247. */
  103248. set: function (speed) {
  103249. this._idleRotationSpeed = speed;
  103250. },
  103251. enumerable: true,
  103252. configurable: true
  103253. });
  103254. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  103255. /**
  103256. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  103257. */
  103258. get: function () {
  103259. return this._idleRotationWaitTime;
  103260. },
  103261. /**
  103262. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  103263. */
  103264. set: function (time) {
  103265. this._idleRotationWaitTime = time;
  103266. },
  103267. enumerable: true,
  103268. configurable: true
  103269. });
  103270. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  103271. /**
  103272. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103273. */
  103274. get: function () {
  103275. return this._idleRotationSpinupTime;
  103276. },
  103277. /**
  103278. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103279. */
  103280. set: function (time) {
  103281. this._idleRotationSpinupTime = time;
  103282. },
  103283. enumerable: true,
  103284. configurable: true
  103285. });
  103286. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  103287. /**
  103288. * Gets a value indicating if the camera is currently rotating because of this behavior
  103289. */
  103290. get: function () {
  103291. return Math.abs(this._cameraRotationSpeed) > 0;
  103292. },
  103293. enumerable: true,
  103294. configurable: true
  103295. });
  103296. AutoRotationBehavior.prototype.init = function () {
  103297. // Do notihng
  103298. };
  103299. AutoRotationBehavior.prototype.attach = function (camera) {
  103300. var _this = this;
  103301. this._attachedCamera = camera;
  103302. var scene = this._attachedCamera.getScene();
  103303. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103304. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103305. _this._isPointerDown = true;
  103306. return;
  103307. }
  103308. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103309. _this._isPointerDown = false;
  103310. }
  103311. });
  103312. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103313. var now = BABYLON.Tools.Now;
  103314. var dt = 0;
  103315. if (_this._lastFrameTime != null) {
  103316. dt = now - _this._lastFrameTime;
  103317. }
  103318. _this._lastFrameTime = now;
  103319. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103320. _this._applyUserInteraction();
  103321. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  103322. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  103323. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  103324. // Step camera rotation by rotation speed
  103325. if (_this._attachedCamera) {
  103326. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  103327. }
  103328. });
  103329. };
  103330. AutoRotationBehavior.prototype.detach = function () {
  103331. if (!this._attachedCamera) {
  103332. return;
  103333. }
  103334. var scene = this._attachedCamera.getScene();
  103335. if (this._onPrePointerObservableObserver) {
  103336. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103337. }
  103338. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103339. this._attachedCamera = null;
  103340. };
  103341. /**
  103342. * Returns true if user is scrolling.
  103343. * @return true if user is scrolling.
  103344. */
  103345. AutoRotationBehavior.prototype._userIsZooming = function () {
  103346. if (!this._attachedCamera) {
  103347. return false;
  103348. }
  103349. return this._attachedCamera.inertialRadiusOffset !== 0;
  103350. };
  103351. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  103352. if (!this._attachedCamera) {
  103353. return false;
  103354. }
  103355. var zoomHasHitLimit = false;
  103356. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  103357. zoomHasHitLimit = true;
  103358. }
  103359. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  103360. this._lastFrameRadius = this._attachedCamera.radius;
  103361. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  103362. };
  103363. /**
  103364. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103365. */
  103366. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  103367. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  103368. this._lastInteractionTime = BABYLON.Tools.Now;
  103369. }
  103370. };
  103371. // Tools
  103372. AutoRotationBehavior.prototype._userIsMoving = function () {
  103373. if (!this._attachedCamera) {
  103374. return false;
  103375. }
  103376. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103377. this._attachedCamera.inertialBetaOffset !== 0 ||
  103378. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103379. this._attachedCamera.inertialPanningX !== 0 ||
  103380. this._attachedCamera.inertialPanningY !== 0 ||
  103381. this._isPointerDown;
  103382. };
  103383. return AutoRotationBehavior;
  103384. }());
  103385. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  103386. })(BABYLON || (BABYLON = {}));
  103387. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  103388. var BABYLON;
  103389. (function (BABYLON) {
  103390. var NullEngineOptions = /** @class */ (function () {
  103391. function NullEngineOptions() {
  103392. this.renderWidth = 512;
  103393. this.renderHeight = 256;
  103394. this.textureSize = 512;
  103395. this.deterministicLockstep = false;
  103396. this.lockstepMaxSteps = 4;
  103397. }
  103398. return NullEngineOptions;
  103399. }());
  103400. BABYLON.NullEngineOptions = NullEngineOptions;
  103401. /**
  103402. * The null engine class provides support for headless version of babylon.js.
  103403. * This can be used in server side scenario or for testing purposes
  103404. */
  103405. var NullEngine = /** @class */ (function (_super) {
  103406. __extends(NullEngine, _super);
  103407. function NullEngine(options) {
  103408. if (options === void 0) { options = new NullEngineOptions(); }
  103409. var _this = _super.call(this, null) || this;
  103410. if (options.deterministicLockstep === undefined) {
  103411. options.deterministicLockstep = false;
  103412. }
  103413. if (options.lockstepMaxSteps === undefined) {
  103414. options.lockstepMaxSteps = 4;
  103415. }
  103416. _this._options = options;
  103417. // Init caps
  103418. // We consider we are on a webgl1 capable device
  103419. _this._caps = new BABYLON.EngineCapabilities();
  103420. _this._caps.maxTexturesImageUnits = 16;
  103421. _this._caps.maxVertexTextureImageUnits = 16;
  103422. _this._caps.maxTextureSize = 512;
  103423. _this._caps.maxCubemapTextureSize = 512;
  103424. _this._caps.maxRenderTextureSize = 512;
  103425. _this._caps.maxVertexAttribs = 16;
  103426. _this._caps.maxVaryingVectors = 16;
  103427. _this._caps.maxFragmentUniformVectors = 16;
  103428. _this._caps.maxVertexUniformVectors = 16;
  103429. // Extensions
  103430. _this._caps.standardDerivatives = false;
  103431. _this._caps.astc = null;
  103432. _this._caps.s3tc = null;
  103433. _this._caps.pvrtc = null;
  103434. _this._caps.etc1 = null;
  103435. _this._caps.etc2 = null;
  103436. _this._caps.textureAnisotropicFilterExtension = null;
  103437. _this._caps.maxAnisotropy = 0;
  103438. _this._caps.uintIndices = false;
  103439. _this._caps.fragmentDepthSupported = false;
  103440. _this._caps.highPrecisionShaderSupported = true;
  103441. _this._caps.colorBufferFloat = false;
  103442. _this._caps.textureFloat = false;
  103443. _this._caps.textureFloatLinearFiltering = false;
  103444. _this._caps.textureFloatRender = false;
  103445. _this._caps.textureHalfFloat = false;
  103446. _this._caps.textureHalfFloatLinearFiltering = false;
  103447. _this._caps.textureHalfFloatRender = false;
  103448. _this._caps.textureLOD = false;
  103449. _this._caps.drawBuffersExtension = false;
  103450. _this._caps.depthTextureExtension = false;
  103451. _this._caps.vertexArrayObject = false;
  103452. _this._caps.instancedArrays = false;
  103453. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  103454. // Wrappers
  103455. if (typeof URL === "undefined") {
  103456. URL = {
  103457. createObjectURL: function () { },
  103458. revokeObjectURL: function () { }
  103459. };
  103460. }
  103461. if (typeof Blob === "undefined") {
  103462. Blob = function () { };
  103463. }
  103464. return _this;
  103465. }
  103466. NullEngine.prototype.isDeterministicLockStep = function () {
  103467. return this._options.deterministicLockstep;
  103468. };
  103469. NullEngine.prototype.getLockstepMaxSteps = function () {
  103470. return this._options.lockstepMaxSteps;
  103471. };
  103472. NullEngine.prototype.getHardwareScalingLevel = function () {
  103473. return 1.0;
  103474. };
  103475. NullEngine.prototype.createVertexBuffer = function (vertices) {
  103476. return {
  103477. capacity: 0,
  103478. references: 1,
  103479. is32Bits: false
  103480. };
  103481. };
  103482. NullEngine.prototype.createIndexBuffer = function (indices) {
  103483. return {
  103484. capacity: 0,
  103485. references: 1,
  103486. is32Bits: false
  103487. };
  103488. };
  103489. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  103490. if (stencil === void 0) { stencil = false; }
  103491. };
  103492. NullEngine.prototype.getRenderWidth = function (useScreen) {
  103493. if (useScreen === void 0) { useScreen = false; }
  103494. if (!useScreen && this._currentRenderTarget) {
  103495. return this._currentRenderTarget.width;
  103496. }
  103497. return this._options.renderWidth;
  103498. };
  103499. NullEngine.prototype.getRenderHeight = function (useScreen) {
  103500. if (useScreen === void 0) { useScreen = false; }
  103501. if (!useScreen && this._currentRenderTarget) {
  103502. return this._currentRenderTarget.height;
  103503. }
  103504. return this._options.renderHeight;
  103505. };
  103506. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  103507. this._cachedViewport = viewport;
  103508. };
  103509. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  103510. return {
  103511. transformFeedback: null,
  103512. __SPECTOR_rebuildProgram: null
  103513. };
  103514. };
  103515. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  103516. return [];
  103517. };
  103518. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  103519. return [];
  103520. };
  103521. NullEngine.prototype.bindSamplers = function (effect) {
  103522. this._currentEffect = null;
  103523. };
  103524. NullEngine.prototype.enableEffect = function (effect) {
  103525. this._currentEffect = effect;
  103526. if (effect.onBind) {
  103527. effect.onBind(effect);
  103528. }
  103529. if (effect._onBindObservable) {
  103530. effect._onBindObservable.notifyObservers(effect);
  103531. }
  103532. };
  103533. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  103534. if (zOffset === void 0) { zOffset = 0; }
  103535. if (reverseSide === void 0) { reverseSide = false; }
  103536. };
  103537. NullEngine.prototype.setIntArray = function (uniform, array) {
  103538. };
  103539. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  103540. };
  103541. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  103542. };
  103543. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  103544. };
  103545. NullEngine.prototype.setFloatArray = function (uniform, array) {
  103546. };
  103547. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  103548. };
  103549. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  103550. };
  103551. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  103552. };
  103553. NullEngine.prototype.setArray = function (uniform, array) {
  103554. };
  103555. NullEngine.prototype.setArray2 = function (uniform, array) {
  103556. };
  103557. NullEngine.prototype.setArray3 = function (uniform, array) {
  103558. };
  103559. NullEngine.prototype.setArray4 = function (uniform, array) {
  103560. };
  103561. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  103562. };
  103563. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  103564. };
  103565. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  103566. };
  103567. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  103568. };
  103569. NullEngine.prototype.setFloat = function (uniform, value) {
  103570. };
  103571. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  103572. };
  103573. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  103574. };
  103575. NullEngine.prototype.setBool = function (uniform, bool) {
  103576. };
  103577. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  103578. };
  103579. NullEngine.prototype.setColor3 = function (uniform, color3) {
  103580. };
  103581. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  103582. };
  103583. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  103584. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  103585. if (this._alphaMode === mode) {
  103586. return;
  103587. }
  103588. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  103589. if (!noDepthWriteChange) {
  103590. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  103591. }
  103592. this._alphaMode = mode;
  103593. };
  103594. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  103595. };
  103596. NullEngine.prototype.wipeCaches = function (bruteForce) {
  103597. if (this.preventCacheWipeBetweenFrames) {
  103598. return;
  103599. }
  103600. this.resetTextureCache();
  103601. this._currentEffect = null;
  103602. if (bruteForce) {
  103603. this._currentProgram = null;
  103604. this._stencilState.reset();
  103605. this._depthCullingState.reset();
  103606. this._alphaState.reset();
  103607. }
  103608. this._cachedVertexBuffers = null;
  103609. this._cachedIndexBuffer = null;
  103610. this._cachedEffectForVertexBuffers = null;
  103611. };
  103612. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  103613. };
  103614. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  103615. };
  103616. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  103617. };
  103618. /** @hidden */
  103619. NullEngine.prototype._createTexture = function () {
  103620. return {};
  103621. };
  103622. /** @hidden */
  103623. NullEngine.prototype._releaseTexture = function (texture) {
  103624. };
  103625. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  103626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103627. if (onLoad === void 0) { onLoad = null; }
  103628. if (onError === void 0) { onError = null; }
  103629. if (buffer === void 0) { buffer = null; }
  103630. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  103631. var url = String(urlArg);
  103632. texture.url = url;
  103633. texture.generateMipMaps = !noMipmap;
  103634. texture.samplingMode = samplingMode;
  103635. texture.invertY = invertY;
  103636. texture.baseWidth = this._options.textureSize;
  103637. texture.baseHeight = this._options.textureSize;
  103638. texture.width = this._options.textureSize;
  103639. texture.height = this._options.textureSize;
  103640. if (format) {
  103641. texture.format = format;
  103642. }
  103643. texture.isReady = true;
  103644. if (onLoad) {
  103645. onLoad();
  103646. }
  103647. this._internalTexturesCache.push(texture);
  103648. return texture;
  103649. };
  103650. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  103651. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  103652. if (options !== undefined && typeof options === "object") {
  103653. fullOptions.generateMipMaps = options.generateMipMaps;
  103654. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  103655. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  103656. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  103657. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  103658. }
  103659. else {
  103660. fullOptions.generateMipMaps = options;
  103661. fullOptions.generateDepthBuffer = true;
  103662. fullOptions.generateStencilBuffer = false;
  103663. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103664. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103665. }
  103666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  103667. var width = size.width || size;
  103668. var height = size.height || size;
  103669. texture._depthStencilBuffer = {};
  103670. texture._framebuffer = {};
  103671. texture.baseWidth = width;
  103672. texture.baseHeight = height;
  103673. texture.width = width;
  103674. texture.height = height;
  103675. texture.isReady = true;
  103676. texture.samples = 1;
  103677. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  103678. texture.samplingMode = fullOptions.samplingMode;
  103679. texture.type = fullOptions.type;
  103680. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  103681. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  103682. this._internalTexturesCache.push(texture);
  103683. return texture;
  103684. };
  103685. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  103686. texture.samplingMode = samplingMode;
  103687. };
  103688. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  103689. if (this._currentRenderTarget) {
  103690. this.unBindFramebuffer(this._currentRenderTarget);
  103691. }
  103692. this._currentRenderTarget = texture;
  103693. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  103694. if (this._cachedViewport && !forceFullscreenViewport) {
  103695. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  103696. }
  103697. };
  103698. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  103699. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  103700. this._currentRenderTarget = null;
  103701. if (onBeforeUnbind) {
  103702. if (texture._MSAAFramebuffer) {
  103703. this._currentFramebuffer = texture._framebuffer;
  103704. }
  103705. onBeforeUnbind();
  103706. }
  103707. this._currentFramebuffer = null;
  103708. };
  103709. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  103710. var vbo = {
  103711. capacity: 1,
  103712. references: 1,
  103713. is32Bits: false
  103714. };
  103715. return vbo;
  103716. };
  103717. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  103718. if (premulAlpha === void 0) { premulAlpha = false; }
  103719. };
  103720. /**
  103721. * @hidden
  103722. * Get the current error code of the webGL context
  103723. * @returns the error code
  103724. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  103725. */
  103726. NullEngine.prototype.getError = function () {
  103727. return 0;
  103728. };
  103729. /** @hidden */
  103730. NullEngine.prototype._getUnpackAlignement = function () {
  103731. return 1;
  103732. };
  103733. /** @hidden */
  103734. NullEngine.prototype._unpackFlipY = function (value) {
  103735. };
  103736. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  103737. if (offset === void 0) { offset = 0; }
  103738. };
  103739. /**
  103740. * Updates a dynamic vertex buffer.
  103741. * @param vertexBuffer the vertex buffer to update
  103742. * @param data the data used to update the vertex buffer
  103743. * @param byteOffset the byte offset of the data (optional)
  103744. * @param byteLength the byte length of the data (optional)
  103745. */
  103746. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  103747. };
  103748. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  103749. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  103750. this._boundTexturesCache[this._activeChannel] = texture;
  103751. return true;
  103752. }
  103753. return false;
  103754. };
  103755. /** @hidden */
  103756. NullEngine.prototype._bindTexture = function (channel, texture) {
  103757. if (channel < 0) {
  103758. return;
  103759. }
  103760. this._bindTextureDirectly(0, texture);
  103761. };
  103762. /** @hidden */
  103763. NullEngine.prototype._releaseBuffer = function (buffer) {
  103764. buffer.references--;
  103765. if (buffer.references === 0) {
  103766. return true;
  103767. }
  103768. return false;
  103769. };
  103770. NullEngine.prototype.releaseEffects = function () {
  103771. };
  103772. NullEngine.prototype.displayLoadingUI = function () {
  103773. };
  103774. NullEngine.prototype.hideLoadingUI = function () {
  103775. };
  103776. /** @hidden */
  103777. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  103778. if (faceIndex === void 0) { faceIndex = 0; }
  103779. if (lod === void 0) { lod = 0; }
  103780. };
  103781. /** @hidden */
  103782. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  103783. if (faceIndex === void 0) { faceIndex = 0; }
  103784. if (lod === void 0) { lod = 0; }
  103785. };
  103786. /** @hidden */
  103787. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  103788. if (faceIndex === void 0) { faceIndex = 0; }
  103789. if (lod === void 0) { lod = 0; }
  103790. };
  103791. /** @hidden */
  103792. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  103793. if (faceIndex === void 0) { faceIndex = 0; }
  103794. if (lod === void 0) { lod = 0; }
  103795. };
  103796. return NullEngine;
  103797. }(BABYLON.Engine));
  103798. BABYLON.NullEngine = NullEngine;
  103799. })(BABYLON || (BABYLON = {}));
  103800. //# sourceMappingURL=babylon.nullEngine.js.map
  103801. var BABYLON;
  103802. (function (BABYLON) {
  103803. /**
  103804. * This class can be used to get instrumentation data from a Babylon engine
  103805. */
  103806. var EngineInstrumentation = /** @class */ (function () {
  103807. function EngineInstrumentation(engine) {
  103808. this.engine = engine;
  103809. this._captureGPUFrameTime = false;
  103810. this._gpuFrameTime = new BABYLON.PerfCounter();
  103811. this._captureShaderCompilationTime = false;
  103812. this._shaderCompilationTime = new BABYLON.PerfCounter();
  103813. // Observers
  103814. this._onBeginFrameObserver = null;
  103815. this._onEndFrameObserver = null;
  103816. this._onBeforeShaderCompilationObserver = null;
  103817. this._onAfterShaderCompilationObserver = null;
  103818. }
  103819. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  103820. // Properties
  103821. /**
  103822. * Gets the perf counter used for GPU frame time
  103823. */
  103824. get: function () {
  103825. return this._gpuFrameTime;
  103826. },
  103827. enumerable: true,
  103828. configurable: true
  103829. });
  103830. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  103831. /**
  103832. * Gets the GPU frame time capture status
  103833. */
  103834. get: function () {
  103835. return this._captureGPUFrameTime;
  103836. },
  103837. /**
  103838. * Enable or disable the GPU frame time capture
  103839. */
  103840. set: function (value) {
  103841. var _this = this;
  103842. if (value === this._captureGPUFrameTime) {
  103843. return;
  103844. }
  103845. this._captureGPUFrameTime = value;
  103846. if (value) {
  103847. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  103848. if (!_this._gpuFrameTimeToken) {
  103849. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  103850. }
  103851. });
  103852. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  103853. if (!_this._gpuFrameTimeToken) {
  103854. return;
  103855. }
  103856. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  103857. if (time > -1) {
  103858. _this._gpuFrameTimeToken = null;
  103859. _this._gpuFrameTime.fetchNewFrame();
  103860. _this._gpuFrameTime.addCount(time, true);
  103861. }
  103862. });
  103863. }
  103864. else {
  103865. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  103866. this._onBeginFrameObserver = null;
  103867. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  103868. this._onEndFrameObserver = null;
  103869. }
  103870. },
  103871. enumerable: true,
  103872. configurable: true
  103873. });
  103874. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  103875. /**
  103876. * Gets the perf counter used for shader compilation time
  103877. */
  103878. get: function () {
  103879. return this._shaderCompilationTime;
  103880. },
  103881. enumerable: true,
  103882. configurable: true
  103883. });
  103884. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  103885. /**
  103886. * Gets the shader compilation time capture status
  103887. */
  103888. get: function () {
  103889. return this._captureShaderCompilationTime;
  103890. },
  103891. /**
  103892. * Enable or disable the shader compilation time capture
  103893. */
  103894. set: function (value) {
  103895. var _this = this;
  103896. if (value === this._captureShaderCompilationTime) {
  103897. return;
  103898. }
  103899. this._captureShaderCompilationTime = value;
  103900. if (value) {
  103901. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  103902. _this._shaderCompilationTime.fetchNewFrame();
  103903. _this._shaderCompilationTime.beginMonitoring();
  103904. });
  103905. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  103906. _this._shaderCompilationTime.endMonitoring();
  103907. });
  103908. }
  103909. else {
  103910. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  103911. this._onBeforeShaderCompilationObserver = null;
  103912. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  103913. this._onAfterShaderCompilationObserver = null;
  103914. }
  103915. },
  103916. enumerable: true,
  103917. configurable: true
  103918. });
  103919. EngineInstrumentation.prototype.dispose = function () {
  103920. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  103921. this._onBeginFrameObserver = null;
  103922. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  103923. this._onEndFrameObserver = null;
  103924. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  103925. this._onBeforeShaderCompilationObserver = null;
  103926. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  103927. this._onAfterShaderCompilationObserver = null;
  103928. this.engine = null;
  103929. };
  103930. return EngineInstrumentation;
  103931. }());
  103932. BABYLON.EngineInstrumentation = EngineInstrumentation;
  103933. })(BABYLON || (BABYLON = {}));
  103934. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  103935. var BABYLON;
  103936. (function (BABYLON) {
  103937. /**
  103938. * This class can be used to get instrumentation data from a Babylon engine
  103939. */
  103940. var SceneInstrumentation = /** @class */ (function () {
  103941. function SceneInstrumentation(scene) {
  103942. var _this = this;
  103943. this.scene = scene;
  103944. this._captureActiveMeshesEvaluationTime = false;
  103945. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  103946. this._captureRenderTargetsRenderTime = false;
  103947. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  103948. this._captureFrameTime = false;
  103949. this._frameTime = new BABYLON.PerfCounter();
  103950. this._captureRenderTime = false;
  103951. this._renderTime = new BABYLON.PerfCounter();
  103952. this._captureInterFrameTime = false;
  103953. this._interFrameTime = new BABYLON.PerfCounter();
  103954. this._captureParticlesRenderTime = false;
  103955. this._particlesRenderTime = new BABYLON.PerfCounter();
  103956. this._captureSpritesRenderTime = false;
  103957. this._spritesRenderTime = new BABYLON.PerfCounter();
  103958. this._capturePhysicsTime = false;
  103959. this._physicsTime = new BABYLON.PerfCounter();
  103960. this._captureAnimationsTime = false;
  103961. this._animationsTime = new BABYLON.PerfCounter();
  103962. this._captureCameraRenderTime = false;
  103963. this._cameraRenderTime = new BABYLON.PerfCounter();
  103964. // Observers
  103965. this._onBeforeActiveMeshesEvaluationObserver = null;
  103966. this._onAfterActiveMeshesEvaluationObserver = null;
  103967. this._onBeforeRenderTargetsRenderObserver = null;
  103968. this._onAfterRenderTargetsRenderObserver = null;
  103969. this._onAfterRenderObserver = null;
  103970. this._onBeforeDrawPhaseObserver = null;
  103971. this._onAfterDrawPhaseObserver = null;
  103972. this._onBeforeAnimationsObserver = null;
  103973. this._onBeforeParticlesRenderingObserver = null;
  103974. this._onAfterParticlesRenderingObserver = null;
  103975. this._onBeforeSpritesRenderingObserver = null;
  103976. this._onAfterSpritesRenderingObserver = null;
  103977. this._onBeforePhysicsObserver = null;
  103978. this._onAfterPhysicsObserver = null;
  103979. this._onAfterAnimationsObserver = null;
  103980. this._onBeforeCameraRenderObserver = null;
  103981. this._onAfterCameraRenderObserver = null;
  103982. // Before render
  103983. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  103984. if (_this._captureActiveMeshesEvaluationTime) {
  103985. _this._activeMeshesEvaluationTime.fetchNewFrame();
  103986. }
  103987. if (_this._captureRenderTargetsRenderTime) {
  103988. _this._renderTargetsRenderTime.fetchNewFrame();
  103989. }
  103990. if (_this._captureFrameTime) {
  103991. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  103992. _this._frameTime.beginMonitoring();
  103993. }
  103994. if (_this._captureInterFrameTime) {
  103995. _this._interFrameTime.endMonitoring();
  103996. }
  103997. if (_this._captureParticlesRenderTime) {
  103998. _this._particlesRenderTime.fetchNewFrame();
  103999. }
  104000. if (_this._captureSpritesRenderTime) {
  104001. _this._spritesRenderTime.fetchNewFrame();
  104002. }
  104003. if (_this._captureAnimationsTime) {
  104004. _this._animationsTime.beginMonitoring();
  104005. }
  104006. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  104007. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  104008. });
  104009. // After render
  104010. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  104011. if (_this._captureFrameTime) {
  104012. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  104013. _this._frameTime.endMonitoring();
  104014. }
  104015. if (_this._captureRenderTime) {
  104016. _this._renderTime.endMonitoring(false);
  104017. }
  104018. if (_this._captureInterFrameTime) {
  104019. _this._interFrameTime.beginMonitoring();
  104020. }
  104021. });
  104022. }
  104023. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  104024. // Properties
  104025. /**
  104026. * Gets the perf counter used for active meshes evaluation time
  104027. */
  104028. get: function () {
  104029. return this._activeMeshesEvaluationTime;
  104030. },
  104031. enumerable: true,
  104032. configurable: true
  104033. });
  104034. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  104035. /**
  104036. * Gets the active meshes evaluation time capture status
  104037. */
  104038. get: function () {
  104039. return this._captureActiveMeshesEvaluationTime;
  104040. },
  104041. /**
  104042. * Enable or disable the active meshes evaluation time capture
  104043. */
  104044. set: function (value) {
  104045. var _this = this;
  104046. if (value === this._captureActiveMeshesEvaluationTime) {
  104047. return;
  104048. }
  104049. this._captureActiveMeshesEvaluationTime = value;
  104050. if (value) {
  104051. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  104052. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  104053. _this._activeMeshesEvaluationTime.beginMonitoring();
  104054. });
  104055. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  104056. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  104057. _this._activeMeshesEvaluationTime.endMonitoring();
  104058. });
  104059. }
  104060. else {
  104061. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104062. this._onBeforeActiveMeshesEvaluationObserver = null;
  104063. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104064. this._onAfterActiveMeshesEvaluationObserver = null;
  104065. }
  104066. },
  104067. enumerable: true,
  104068. configurable: true
  104069. });
  104070. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  104071. /**
  104072. * Gets the perf counter used for render targets render time
  104073. */
  104074. get: function () {
  104075. return this._renderTargetsRenderTime;
  104076. },
  104077. enumerable: true,
  104078. configurable: true
  104079. });
  104080. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  104081. /**
  104082. * Gets the render targets render time capture status
  104083. */
  104084. get: function () {
  104085. return this._captureRenderTargetsRenderTime;
  104086. },
  104087. /**
  104088. * Enable or disable the render targets render time capture
  104089. */
  104090. set: function (value) {
  104091. var _this = this;
  104092. if (value === this._captureRenderTargetsRenderTime) {
  104093. return;
  104094. }
  104095. this._captureRenderTargetsRenderTime = value;
  104096. if (value) {
  104097. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  104098. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  104099. _this._renderTargetsRenderTime.beginMonitoring();
  104100. });
  104101. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  104102. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  104103. _this._renderTargetsRenderTime.endMonitoring(false);
  104104. });
  104105. }
  104106. else {
  104107. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104108. this._onBeforeRenderTargetsRenderObserver = null;
  104109. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104110. this._onAfterRenderTargetsRenderObserver = null;
  104111. }
  104112. },
  104113. enumerable: true,
  104114. configurable: true
  104115. });
  104116. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  104117. /**
  104118. * Gets the perf counter used for particles render time
  104119. */
  104120. get: function () {
  104121. return this._particlesRenderTime;
  104122. },
  104123. enumerable: true,
  104124. configurable: true
  104125. });
  104126. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  104127. /**
  104128. * Gets the particles render time capture status
  104129. */
  104130. get: function () {
  104131. return this._captureParticlesRenderTime;
  104132. },
  104133. /**
  104134. * Enable or disable the particles render time capture
  104135. */
  104136. set: function (value) {
  104137. var _this = this;
  104138. if (value === this._captureParticlesRenderTime) {
  104139. return;
  104140. }
  104141. this._captureParticlesRenderTime = value;
  104142. if (value) {
  104143. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  104144. BABYLON.Tools.StartPerformanceCounter("Particles");
  104145. _this._particlesRenderTime.beginMonitoring();
  104146. });
  104147. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  104148. BABYLON.Tools.EndPerformanceCounter("Particles");
  104149. _this._particlesRenderTime.endMonitoring(false);
  104150. });
  104151. }
  104152. else {
  104153. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104154. this._onBeforeParticlesRenderingObserver = null;
  104155. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104156. this._onAfterParticlesRenderingObserver = null;
  104157. }
  104158. },
  104159. enumerable: true,
  104160. configurable: true
  104161. });
  104162. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  104163. /**
  104164. * Gets the perf counter used for sprites render time
  104165. */
  104166. get: function () {
  104167. return this._spritesRenderTime;
  104168. },
  104169. enumerable: true,
  104170. configurable: true
  104171. });
  104172. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  104173. /**
  104174. * Gets the sprites render time capture status
  104175. */
  104176. get: function () {
  104177. return this._captureSpritesRenderTime;
  104178. },
  104179. /**
  104180. * Enable or disable the sprites render time capture
  104181. */
  104182. set: function (value) {
  104183. var _this = this;
  104184. if (value === this._captureSpritesRenderTime) {
  104185. return;
  104186. }
  104187. this._captureSpritesRenderTime = value;
  104188. if (value) {
  104189. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  104190. BABYLON.Tools.StartPerformanceCounter("Sprites");
  104191. _this._spritesRenderTime.beginMonitoring();
  104192. });
  104193. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  104194. BABYLON.Tools.EndPerformanceCounter("Sprites");
  104195. _this._spritesRenderTime.endMonitoring(false);
  104196. });
  104197. }
  104198. else {
  104199. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104200. this._onBeforeSpritesRenderingObserver = null;
  104201. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104202. this._onAfterSpritesRenderingObserver = null;
  104203. }
  104204. },
  104205. enumerable: true,
  104206. configurable: true
  104207. });
  104208. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  104209. /**
  104210. * Gets the perf counter used for physics time
  104211. */
  104212. get: function () {
  104213. return this._physicsTime;
  104214. },
  104215. enumerable: true,
  104216. configurable: true
  104217. });
  104218. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  104219. /**
  104220. * Gets the physics time capture status
  104221. */
  104222. get: function () {
  104223. return this._capturePhysicsTime;
  104224. },
  104225. /**
  104226. * Enable or disable the physics time capture
  104227. */
  104228. set: function (value) {
  104229. var _this = this;
  104230. if (value === this._capturePhysicsTime) {
  104231. return;
  104232. }
  104233. this._capturePhysicsTime = value;
  104234. if (value) {
  104235. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  104236. BABYLON.Tools.StartPerformanceCounter("Physics");
  104237. _this._physicsTime.beginMonitoring();
  104238. });
  104239. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  104240. BABYLON.Tools.EndPerformanceCounter("Physics");
  104241. _this._physicsTime.endMonitoring();
  104242. });
  104243. }
  104244. else {
  104245. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104246. this._onBeforePhysicsObserver = null;
  104247. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104248. this._onAfterPhysicsObserver = null;
  104249. }
  104250. },
  104251. enumerable: true,
  104252. configurable: true
  104253. });
  104254. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  104255. /**
  104256. * Gets the perf counter used for animations time
  104257. */
  104258. get: function () {
  104259. return this._animationsTime;
  104260. },
  104261. enumerable: true,
  104262. configurable: true
  104263. });
  104264. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  104265. /**
  104266. * Gets the animations time capture status
  104267. */
  104268. get: function () {
  104269. return this._captureAnimationsTime;
  104270. },
  104271. /**
  104272. * Enable or disable the animations time capture
  104273. */
  104274. set: function (value) {
  104275. var _this = this;
  104276. if (value === this._captureAnimationsTime) {
  104277. return;
  104278. }
  104279. this._captureAnimationsTime = value;
  104280. if (value) {
  104281. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  104282. _this._animationsTime.endMonitoring();
  104283. });
  104284. }
  104285. else {
  104286. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104287. this._onAfterAnimationsObserver = null;
  104288. }
  104289. },
  104290. enumerable: true,
  104291. configurable: true
  104292. });
  104293. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  104294. /**
  104295. * Gets the perf counter used for frame time capture
  104296. */
  104297. get: function () {
  104298. return this._frameTime;
  104299. },
  104300. enumerable: true,
  104301. configurable: true
  104302. });
  104303. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  104304. /**
  104305. * Gets the frame time capture status
  104306. */
  104307. get: function () {
  104308. return this._captureFrameTime;
  104309. },
  104310. /**
  104311. * Enable or disable the frame time capture
  104312. */
  104313. set: function (value) {
  104314. this._captureFrameTime = value;
  104315. },
  104316. enumerable: true,
  104317. configurable: true
  104318. });
  104319. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  104320. /**
  104321. * Gets the perf counter used for inter-frames time capture
  104322. */
  104323. get: function () {
  104324. return this._interFrameTime;
  104325. },
  104326. enumerable: true,
  104327. configurable: true
  104328. });
  104329. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  104330. /**
  104331. * Gets the inter-frames time capture status
  104332. */
  104333. get: function () {
  104334. return this._captureInterFrameTime;
  104335. },
  104336. /**
  104337. * Enable or disable the inter-frames time capture
  104338. */
  104339. set: function (value) {
  104340. this._captureInterFrameTime = value;
  104341. },
  104342. enumerable: true,
  104343. configurable: true
  104344. });
  104345. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  104346. /**
  104347. * Gets the perf counter used for render time capture
  104348. */
  104349. get: function () {
  104350. return this._renderTime;
  104351. },
  104352. enumerable: true,
  104353. configurable: true
  104354. });
  104355. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  104356. /**
  104357. * Gets the render time capture status
  104358. */
  104359. get: function () {
  104360. return this._captureRenderTime;
  104361. },
  104362. /**
  104363. * Enable or disable the render time capture
  104364. */
  104365. set: function (value) {
  104366. var _this = this;
  104367. if (value === this._captureRenderTime) {
  104368. return;
  104369. }
  104370. this._captureRenderTime = value;
  104371. if (value) {
  104372. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  104373. _this._renderTime.beginMonitoring();
  104374. BABYLON.Tools.StartPerformanceCounter("Main render");
  104375. });
  104376. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  104377. _this._renderTime.endMonitoring(false);
  104378. BABYLON.Tools.EndPerformanceCounter("Main render");
  104379. });
  104380. }
  104381. else {
  104382. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104383. this._onBeforeDrawPhaseObserver = null;
  104384. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104385. this._onAfterDrawPhaseObserver = null;
  104386. }
  104387. },
  104388. enumerable: true,
  104389. configurable: true
  104390. });
  104391. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  104392. /**
  104393. * Gets the perf counter used for camera render time capture
  104394. */
  104395. get: function () {
  104396. return this._cameraRenderTime;
  104397. },
  104398. enumerable: true,
  104399. configurable: true
  104400. });
  104401. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  104402. /**
  104403. * Gets the camera render time capture status
  104404. */
  104405. get: function () {
  104406. return this._captureCameraRenderTime;
  104407. },
  104408. /**
  104409. * Enable or disable the camera render time capture
  104410. */
  104411. set: function (value) {
  104412. var _this = this;
  104413. if (value === this._captureCameraRenderTime) {
  104414. return;
  104415. }
  104416. this._captureCameraRenderTime = value;
  104417. if (value) {
  104418. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  104419. _this._cameraRenderTime.beginMonitoring();
  104420. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  104421. });
  104422. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  104423. _this._cameraRenderTime.endMonitoring(false);
  104424. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  104425. });
  104426. }
  104427. else {
  104428. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104429. this._onBeforeCameraRenderObserver = null;
  104430. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104431. this._onAfterCameraRenderObserver = null;
  104432. }
  104433. },
  104434. enumerable: true,
  104435. configurable: true
  104436. });
  104437. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  104438. /**
  104439. * Gets the perf counter used for draw calls
  104440. */
  104441. get: function () {
  104442. return this.scene.getEngine()._drawCalls;
  104443. },
  104444. enumerable: true,
  104445. configurable: true
  104446. });
  104447. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  104448. /**
  104449. * Gets the perf counter used for texture collisions
  104450. */
  104451. get: function () {
  104452. return this.scene.getEngine()._textureCollisions;
  104453. },
  104454. enumerable: true,
  104455. configurable: true
  104456. });
  104457. SceneInstrumentation.prototype.dispose = function () {
  104458. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104459. this._onAfterRenderObserver = null;
  104460. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104461. this._onBeforeActiveMeshesEvaluationObserver = null;
  104462. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104463. this._onAfterActiveMeshesEvaluationObserver = null;
  104464. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104465. this._onBeforeRenderTargetsRenderObserver = null;
  104466. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104467. this._onAfterRenderTargetsRenderObserver = null;
  104468. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  104469. this._onBeforeAnimationsObserver = null;
  104470. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104471. this._onBeforeParticlesRenderingObserver = null;
  104472. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104473. this._onAfterParticlesRenderingObserver = null;
  104474. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104475. this._onBeforeSpritesRenderingObserver = null;
  104476. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104477. this._onAfterSpritesRenderingObserver = null;
  104478. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104479. this._onBeforeDrawPhaseObserver = null;
  104480. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104481. this._onAfterDrawPhaseObserver = null;
  104482. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104483. this._onBeforePhysicsObserver = null;
  104484. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104485. this._onAfterPhysicsObserver = null;
  104486. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104487. this._onAfterAnimationsObserver = null;
  104488. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104489. this._onBeforeCameraRenderObserver = null;
  104490. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104491. this._onAfterCameraRenderObserver = null;
  104492. this.scene = null;
  104493. };
  104494. return SceneInstrumentation;
  104495. }());
  104496. BABYLON.SceneInstrumentation = SceneInstrumentation;
  104497. })(BABYLON || (BABYLON = {}));
  104498. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  104499. var BABYLON;
  104500. (function (BABYLON) {
  104501. /**
  104502. * @hidden
  104503. **/
  104504. var _TimeToken = /** @class */ (function () {
  104505. function _TimeToken() {
  104506. this._timeElapsedQueryEnded = false;
  104507. }
  104508. return _TimeToken;
  104509. }());
  104510. BABYLON._TimeToken = _TimeToken;
  104511. })(BABYLON || (BABYLON = {}));
  104512. //# sourceMappingURL=babylon.timeToken.js.map
  104513. var BABYLON;
  104514. (function (BABYLON) {
  104515. /**
  104516. * Background material defines definition.
  104517. * @hidden Mainly internal Use
  104518. */
  104519. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  104520. __extends(BackgroundMaterialDefines, _super);
  104521. /**
  104522. * Constructor of the defines.
  104523. */
  104524. function BackgroundMaterialDefines() {
  104525. var _this = _super.call(this) || this;
  104526. /**
  104527. * True if the diffuse texture is in use.
  104528. */
  104529. _this.DIFFUSE = false;
  104530. /**
  104531. * The direct UV channel to use.
  104532. */
  104533. _this.DIFFUSEDIRECTUV = 0;
  104534. /**
  104535. * True if the diffuse texture is in gamma space.
  104536. */
  104537. _this.GAMMADIFFUSE = false;
  104538. /**
  104539. * True if the diffuse texture has opacity in the alpha channel.
  104540. */
  104541. _this.DIFFUSEHASALPHA = false;
  104542. /**
  104543. * True if you want the material to fade to transparent at grazing angle.
  104544. */
  104545. _this.OPACITYFRESNEL = false;
  104546. /**
  104547. * True if an extra blur needs to be added in the reflection.
  104548. */
  104549. _this.REFLECTIONBLUR = false;
  104550. /**
  104551. * True if you want the material to fade to reflection at grazing angle.
  104552. */
  104553. _this.REFLECTIONFRESNEL = false;
  104554. /**
  104555. * True if you want the material to falloff as far as you move away from the scene center.
  104556. */
  104557. _this.REFLECTIONFALLOFF = false;
  104558. /**
  104559. * False if the current Webgl implementation does not support the texture lod extension.
  104560. */
  104561. _this.TEXTURELODSUPPORT = false;
  104562. /**
  104563. * True to ensure the data are premultiplied.
  104564. */
  104565. _this.PREMULTIPLYALPHA = false;
  104566. /**
  104567. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  104568. */
  104569. _this.USERGBCOLOR = false;
  104570. /**
  104571. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  104572. * stays aligned with the desired configuration.
  104573. */
  104574. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  104575. /**
  104576. * True to add noise in order to reduce the banding effect.
  104577. */
  104578. _this.NOISE = false;
  104579. /**
  104580. * is the reflection texture in BGR color scheme?
  104581. * Mainly used to solve a bug in ios10 video tag
  104582. */
  104583. _this.REFLECTIONBGR = false;
  104584. _this.IMAGEPROCESSING = false;
  104585. _this.VIGNETTE = false;
  104586. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  104587. _this.VIGNETTEBLENDMODEOPAQUE = false;
  104588. _this.TONEMAPPING = false;
  104589. _this.TONEMAPPING_ACES = false;
  104590. _this.CONTRAST = false;
  104591. _this.COLORCURVES = false;
  104592. _this.COLORGRADING = false;
  104593. _this.COLORGRADING3D = false;
  104594. _this.SAMPLER3DGREENDEPTH = false;
  104595. _this.SAMPLER3DBGRMAP = false;
  104596. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  104597. _this.EXPOSURE = false;
  104598. // Reflection.
  104599. _this.REFLECTION = false;
  104600. _this.REFLECTIONMAP_3D = false;
  104601. _this.REFLECTIONMAP_SPHERICAL = false;
  104602. _this.REFLECTIONMAP_PLANAR = false;
  104603. _this.REFLECTIONMAP_CUBIC = false;
  104604. _this.REFLECTIONMAP_PROJECTION = false;
  104605. _this.REFLECTIONMAP_SKYBOX = false;
  104606. _this.REFLECTIONMAP_EXPLICIT = false;
  104607. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  104608. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  104609. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  104610. _this.INVERTCUBICMAP = false;
  104611. _this.REFLECTIONMAP_OPPOSITEZ = false;
  104612. _this.LODINREFLECTIONALPHA = false;
  104613. _this.GAMMAREFLECTION = false;
  104614. _this.RGBDREFLECTION = false;
  104615. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  104616. // Default BJS.
  104617. _this.MAINUV1 = false;
  104618. _this.MAINUV2 = false;
  104619. _this.UV1 = false;
  104620. _this.UV2 = false;
  104621. _this.CLIPPLANE = false;
  104622. _this.CLIPPLANE2 = false;
  104623. _this.CLIPPLANE3 = false;
  104624. _this.CLIPPLANE4 = false;
  104625. _this.POINTSIZE = false;
  104626. _this.FOG = false;
  104627. _this.NORMAL = false;
  104628. _this.NUM_BONE_INFLUENCERS = 0;
  104629. _this.BonesPerMesh = 0;
  104630. _this.INSTANCES = false;
  104631. _this.SHADOWFLOAT = false;
  104632. _this.rebuild();
  104633. return _this;
  104634. }
  104635. return BackgroundMaterialDefines;
  104636. }(BABYLON.MaterialDefines));
  104637. /**
  104638. * Background material used to create an efficient environement around your scene.
  104639. */
  104640. var BackgroundMaterial = /** @class */ (function (_super) {
  104641. __extends(BackgroundMaterial, _super);
  104642. /**
  104643. * Instantiates a Background Material in the given scene
  104644. * @param name The friendly name of the material
  104645. * @param scene The scene to add the material to
  104646. */
  104647. function BackgroundMaterial(name, scene) {
  104648. var _this = _super.call(this, name, scene) || this;
  104649. /**
  104650. * Key light Color (multiply against the environement texture)
  104651. */
  104652. _this.primaryColor = BABYLON.Color3.White();
  104653. _this._primaryColorShadowLevel = 0;
  104654. _this._primaryColorHighlightLevel = 0;
  104655. /**
  104656. * Reflection Texture used in the material.
  104657. * Should be author in a specific way for the best result (refer to the documentation).
  104658. */
  104659. _this.reflectionTexture = null;
  104660. /**
  104661. * Reflection Texture level of blur.
  104662. *
  104663. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  104664. * texture twice.
  104665. */
  104666. _this.reflectionBlur = 0;
  104667. /**
  104668. * Diffuse Texture used in the material.
  104669. * Should be author in a specific way for the best result (refer to the documentation).
  104670. */
  104671. _this.diffuseTexture = null;
  104672. _this._shadowLights = null;
  104673. /**
  104674. * Specify the list of lights casting shadow on the material.
  104675. * All scene shadow lights will be included if null.
  104676. */
  104677. _this.shadowLights = null;
  104678. /**
  104679. * Helps adjusting the shadow to a softer level if required.
  104680. * 0 means black shadows and 1 means no shadows.
  104681. */
  104682. _this.shadowLevel = 0;
  104683. /**
  104684. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  104685. * It is usually zero but might be interesting to modify according to your setup.
  104686. */
  104687. _this.sceneCenter = BABYLON.Vector3.Zero();
  104688. /**
  104689. * This helps specifying that the material is falling off to the sky box at grazing angle.
  104690. * This helps ensuring a nice transition when the camera goes under the ground.
  104691. */
  104692. _this.opacityFresnel = true;
  104693. /**
  104694. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  104695. * This helps adding a mirror texture on the ground.
  104696. */
  104697. _this.reflectionFresnel = false;
  104698. /**
  104699. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  104700. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  104701. */
  104702. _this.reflectionFalloffDistance = 0.0;
  104703. /**
  104704. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  104705. */
  104706. _this.reflectionAmount = 1.0;
  104707. /**
  104708. * This specifies the weight of the reflection at grazing angle.
  104709. */
  104710. _this.reflectionReflectance0 = 0.05;
  104711. /**
  104712. * This specifies the weight of the reflection at a perpendicular point of view.
  104713. */
  104714. _this.reflectionReflectance90 = 0.5;
  104715. /**
  104716. * Helps to directly use the maps channels instead of their level.
  104717. */
  104718. _this.useRGBColor = true;
  104719. /**
  104720. * This helps reducing the banding effect that could occur on the background.
  104721. */
  104722. _this.enableNoise = false;
  104723. _this._fovMultiplier = 1.0;
  104724. /**
  104725. * Enable the FOV adjustment feature controlled by fovMultiplier.
  104726. */
  104727. _this.useEquirectangularFOV = false;
  104728. _this._maxSimultaneousLights = 4;
  104729. /**
  104730. * Number of Simultaneous lights allowed on the material.
  104731. */
  104732. _this.maxSimultaneousLights = 4;
  104733. /**
  104734. * Keep track of the image processing observer to allow dispose and replace.
  104735. */
  104736. _this._imageProcessingObserver = null;
  104737. /**
  104738. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  104739. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  104740. */
  104741. _this.switchToBGR = false;
  104742. // Temp values kept as cache in the material.
  104743. _this._renderTargets = new BABYLON.SmartArray(16);
  104744. _this._reflectionControls = BABYLON.Vector4.Zero();
  104745. _this._white = BABYLON.Color3.White();
  104746. _this._primaryShadowColor = BABYLON.Color3.Black();
  104747. _this._primaryHighlightColor = BABYLON.Color3.Black();
  104748. // Setup the default processing configuration to the scene.
  104749. _this._attachImageProcessingConfiguration(null);
  104750. _this.getRenderTargetTextures = function () {
  104751. _this._renderTargets.reset();
  104752. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  104753. _this._renderTargets.push(_this._diffuseTexture);
  104754. }
  104755. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  104756. _this._renderTargets.push(_this._reflectionTexture);
  104757. }
  104758. return _this._renderTargets;
  104759. };
  104760. return _this;
  104761. }
  104762. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  104763. /**
  104764. * Experimental Internal Use Only.
  104765. *
  104766. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  104767. * This acts as a helper to set the primary color to a more "human friendly" value.
  104768. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  104769. * output color as close as possible from the chosen value.
  104770. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  104771. * part of lighting setup.)
  104772. */
  104773. get: function () {
  104774. return this.__perceptualColor;
  104775. },
  104776. set: function (value) {
  104777. this.__perceptualColor = value;
  104778. this._computePrimaryColorFromPerceptualColor();
  104779. this._markAllSubMeshesAsLightsDirty();
  104780. },
  104781. enumerable: true,
  104782. configurable: true
  104783. });
  104784. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  104785. /**
  104786. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  104787. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  104788. */
  104789. get: function () {
  104790. return this._primaryColorShadowLevel;
  104791. },
  104792. set: function (value) {
  104793. this._primaryColorShadowLevel = value;
  104794. this._computePrimaryColors();
  104795. this._markAllSubMeshesAsLightsDirty();
  104796. },
  104797. enumerable: true,
  104798. configurable: true
  104799. });
  104800. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  104801. /**
  104802. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  104803. * The primary color is used at the level chosen to define what the white area would look.
  104804. */
  104805. get: function () {
  104806. return this._primaryColorHighlightLevel;
  104807. },
  104808. set: function (value) {
  104809. this._primaryColorHighlightLevel = value;
  104810. this._computePrimaryColors();
  104811. this._markAllSubMeshesAsLightsDirty();
  104812. },
  104813. enumerable: true,
  104814. configurable: true
  104815. });
  104816. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  104817. /**
  104818. * Sets the reflection reflectance fresnel values according to the default standard
  104819. * empirically know to work well :-)
  104820. */
  104821. set: function (value) {
  104822. var reflectionWeight = value;
  104823. if (reflectionWeight < 0.5) {
  104824. reflectionWeight = reflectionWeight * 2.0;
  104825. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  104826. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  104827. }
  104828. else {
  104829. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  104830. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  104831. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  104832. }
  104833. },
  104834. enumerable: true,
  104835. configurable: true
  104836. });
  104837. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  104838. /**
  104839. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104840. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  104841. * Recommended to be keep at 1.0 except for special cases.
  104842. */
  104843. get: function () {
  104844. return this._fovMultiplier;
  104845. },
  104846. set: function (value) {
  104847. if (isNaN(value)) {
  104848. value = 1.0;
  104849. }
  104850. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  104851. },
  104852. enumerable: true,
  104853. configurable: true
  104854. });
  104855. /**
  104856. * Attaches a new image processing configuration to the PBR Material.
  104857. * @param configuration (if null the scene configuration will be use)
  104858. */
  104859. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  104860. var _this = this;
  104861. if (configuration === this._imageProcessingConfiguration) {
  104862. return;
  104863. }
  104864. // Detaches observer.
  104865. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  104866. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  104867. }
  104868. // Pick the scene configuration if needed.
  104869. if (!configuration) {
  104870. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  104871. }
  104872. else {
  104873. this._imageProcessingConfiguration = configuration;
  104874. }
  104875. // Attaches observer.
  104876. if (this._imageProcessingConfiguration) {
  104877. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  104878. _this._computePrimaryColorFromPerceptualColor();
  104879. _this._markAllSubMeshesAsImageProcessingDirty();
  104880. });
  104881. }
  104882. };
  104883. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  104884. /**
  104885. * Gets the image processing configuration used either in this material.
  104886. */
  104887. get: function () {
  104888. return this._imageProcessingConfiguration;
  104889. },
  104890. /**
  104891. * Sets the Default image processing configuration used either in the this material.
  104892. *
  104893. * If sets to null, the scene one is in use.
  104894. */
  104895. set: function (value) {
  104896. this._attachImageProcessingConfiguration(value);
  104897. // Ensure the effect will be rebuilt.
  104898. this._markAllSubMeshesAsTexturesDirty();
  104899. },
  104900. enumerable: true,
  104901. configurable: true
  104902. });
  104903. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  104904. /**
  104905. * Gets wether the color curves effect is enabled.
  104906. */
  104907. get: function () {
  104908. return this.imageProcessingConfiguration.colorCurvesEnabled;
  104909. },
  104910. /**
  104911. * Sets wether the color curves effect is enabled.
  104912. */
  104913. set: function (value) {
  104914. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  104915. },
  104916. enumerable: true,
  104917. configurable: true
  104918. });
  104919. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  104920. /**
  104921. * Gets wether the color grading effect is enabled.
  104922. */
  104923. get: function () {
  104924. return this.imageProcessingConfiguration.colorGradingEnabled;
  104925. },
  104926. /**
  104927. * Gets wether the color grading effect is enabled.
  104928. */
  104929. set: function (value) {
  104930. this.imageProcessingConfiguration.colorGradingEnabled = value;
  104931. },
  104932. enumerable: true,
  104933. configurable: true
  104934. });
  104935. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  104936. /**
  104937. * Gets wether tonemapping is enabled or not.
  104938. */
  104939. get: function () {
  104940. return this._imageProcessingConfiguration.toneMappingEnabled;
  104941. },
  104942. /**
  104943. * Sets wether tonemapping is enabled or not
  104944. */
  104945. set: function (value) {
  104946. this._imageProcessingConfiguration.toneMappingEnabled = value;
  104947. },
  104948. enumerable: true,
  104949. configurable: true
  104950. });
  104951. ;
  104952. ;
  104953. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  104954. /**
  104955. * The camera exposure used on this material.
  104956. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  104957. * This corresponds to a photographic exposure.
  104958. */
  104959. get: function () {
  104960. return this._imageProcessingConfiguration.exposure;
  104961. },
  104962. /**
  104963. * The camera exposure used on this material.
  104964. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  104965. * This corresponds to a photographic exposure.
  104966. */
  104967. set: function (value) {
  104968. this._imageProcessingConfiguration.exposure = value;
  104969. },
  104970. enumerable: true,
  104971. configurable: true
  104972. });
  104973. ;
  104974. ;
  104975. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  104976. /**
  104977. * Gets The camera contrast used on this material.
  104978. */
  104979. get: function () {
  104980. return this._imageProcessingConfiguration.contrast;
  104981. },
  104982. /**
  104983. * Sets The camera contrast used on this material.
  104984. */
  104985. set: function (value) {
  104986. this._imageProcessingConfiguration.contrast = value;
  104987. },
  104988. enumerable: true,
  104989. configurable: true
  104990. });
  104991. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  104992. /**
  104993. * Gets the Color Grading 2D Lookup Texture.
  104994. */
  104995. get: function () {
  104996. return this._imageProcessingConfiguration.colorGradingTexture;
  104997. },
  104998. /**
  104999. * Sets the Color Grading 2D Lookup Texture.
  105000. */
  105001. set: function (value) {
  105002. this.imageProcessingConfiguration.colorGradingTexture = value;
  105003. },
  105004. enumerable: true,
  105005. configurable: true
  105006. });
  105007. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  105008. /**
  105009. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105010. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105011. * 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;
  105012. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105013. */
  105014. get: function () {
  105015. return this.imageProcessingConfiguration.colorCurves;
  105016. },
  105017. /**
  105018. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105019. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105020. * 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;
  105021. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105022. */
  105023. set: function (value) {
  105024. this.imageProcessingConfiguration.colorCurves = value;
  105025. },
  105026. enumerable: true,
  105027. configurable: true
  105028. });
  105029. /**
  105030. * The entire material has been created in order to prevent overdraw.
  105031. * @returns false
  105032. */
  105033. BackgroundMaterial.prototype.needAlphaTesting = function () {
  105034. return true;
  105035. };
  105036. /**
  105037. * The entire material has been created in order to prevent overdraw.
  105038. * @returns true if blending is enable
  105039. */
  105040. BackgroundMaterial.prototype.needAlphaBlending = function () {
  105041. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  105042. };
  105043. /**
  105044. * Checks wether the material is ready to be rendered for a given mesh.
  105045. * @param mesh The mesh to render
  105046. * @param subMesh The submesh to check against
  105047. * @param useInstances Specify wether or not the material is used with instances
  105048. * @returns true if all the dependencies are ready (Textures, Effects...)
  105049. */
  105050. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  105051. var _this = this;
  105052. if (useInstances === void 0) { useInstances = false; }
  105053. if (subMesh.effect && this.isFrozen) {
  105054. if (this._wasPreviouslyReady) {
  105055. return true;
  105056. }
  105057. }
  105058. if (!subMesh._materialDefines) {
  105059. subMesh._materialDefines = new BackgroundMaterialDefines();
  105060. }
  105061. var scene = this.getScene();
  105062. var defines = subMesh._materialDefines;
  105063. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  105064. if (defines._renderId === scene.getRenderId()) {
  105065. return true;
  105066. }
  105067. }
  105068. var engine = scene.getEngine();
  105069. // Lights
  105070. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  105071. defines._needNormals = true;
  105072. // Textures
  105073. if (defines._areTexturesDirty) {
  105074. defines._needUVs = false;
  105075. if (scene.texturesEnabled) {
  105076. if (scene.getEngine().getCaps().textureLOD) {
  105077. defines.TEXTURELODSUPPORT = true;
  105078. }
  105079. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105080. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  105081. return false;
  105082. }
  105083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  105084. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  105085. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  105086. defines.OPACITYFRESNEL = this._opacityFresnel;
  105087. }
  105088. else {
  105089. defines.DIFFUSE = false;
  105090. defines.DIFFUSEHASALPHA = false;
  105091. defines.GAMMADIFFUSE = false;
  105092. defines.OPACITYFRESNEL = false;
  105093. }
  105094. var reflectionTexture = this._reflectionTexture;
  105095. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105096. if (!reflectionTexture.isReadyOrNotBlocking()) {
  105097. return false;
  105098. }
  105099. defines.REFLECTION = true;
  105100. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  105101. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  105102. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  105103. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  105104. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  105105. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  105106. defines.REFLECTIONBGR = this.switchToBGR;
  105107. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  105108. defines.INVERTCUBICMAP = true;
  105109. }
  105110. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  105111. switch (reflectionTexture.coordinatesMode) {
  105112. case BABYLON.Texture.EXPLICIT_MODE:
  105113. defines.REFLECTIONMAP_EXPLICIT = true;
  105114. break;
  105115. case BABYLON.Texture.PLANAR_MODE:
  105116. defines.REFLECTIONMAP_PLANAR = true;
  105117. break;
  105118. case BABYLON.Texture.PROJECTION_MODE:
  105119. defines.REFLECTIONMAP_PROJECTION = true;
  105120. break;
  105121. case BABYLON.Texture.SKYBOX_MODE:
  105122. defines.REFLECTIONMAP_SKYBOX = true;
  105123. break;
  105124. case BABYLON.Texture.SPHERICAL_MODE:
  105125. defines.REFLECTIONMAP_SPHERICAL = true;
  105126. break;
  105127. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  105128. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  105129. break;
  105130. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  105131. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  105132. break;
  105133. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  105134. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  105135. break;
  105136. case BABYLON.Texture.CUBIC_MODE:
  105137. case BABYLON.Texture.INVCUBIC_MODE:
  105138. default:
  105139. defines.REFLECTIONMAP_CUBIC = true;
  105140. break;
  105141. }
  105142. if (this.reflectionFresnel) {
  105143. defines.REFLECTIONFRESNEL = true;
  105144. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  105145. this._reflectionControls.x = this.reflectionAmount;
  105146. this._reflectionControls.y = this.reflectionReflectance0;
  105147. this._reflectionControls.z = this.reflectionReflectance90;
  105148. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  105149. }
  105150. else {
  105151. defines.REFLECTIONFRESNEL = false;
  105152. defines.REFLECTIONFALLOFF = false;
  105153. }
  105154. }
  105155. else {
  105156. defines.REFLECTION = false;
  105157. defines.REFLECTIONFRESNEL = false;
  105158. defines.REFLECTIONFALLOFF = false;
  105159. defines.REFLECTIONBLUR = false;
  105160. defines.REFLECTIONMAP_3D = false;
  105161. defines.REFLECTIONMAP_SPHERICAL = false;
  105162. defines.REFLECTIONMAP_PLANAR = false;
  105163. defines.REFLECTIONMAP_CUBIC = false;
  105164. defines.REFLECTIONMAP_PROJECTION = false;
  105165. defines.REFLECTIONMAP_SKYBOX = false;
  105166. defines.REFLECTIONMAP_EXPLICIT = false;
  105167. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105168. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105169. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105170. defines.INVERTCUBICMAP = false;
  105171. defines.REFLECTIONMAP_OPPOSITEZ = false;
  105172. defines.LODINREFLECTIONALPHA = false;
  105173. defines.GAMMAREFLECTION = false;
  105174. defines.RGBDREFLECTION = false;
  105175. }
  105176. }
  105177. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  105178. defines.USERGBCOLOR = this._useRGBColor;
  105179. defines.NOISE = this._enableNoise;
  105180. }
  105181. if (defines._areLightsDirty) {
  105182. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  105183. }
  105184. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  105185. if (!this._imageProcessingConfiguration.isReady()) {
  105186. return false;
  105187. }
  105188. this._imageProcessingConfiguration.prepareDefines(defines);
  105189. }
  105190. // Misc.
  105191. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  105192. // Values that need to be evaluated on every frame
  105193. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  105194. // Attribs
  105195. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  105196. if (mesh) {
  105197. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105198. mesh.createNormals(true);
  105199. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  105200. }
  105201. }
  105202. }
  105203. // Get correct effect
  105204. if (defines.isDirty) {
  105205. defines.markAsProcessed();
  105206. scene.resetCachedMaterial();
  105207. // Fallbacks
  105208. var fallbacks = new BABYLON.EffectFallbacks();
  105209. if (defines.FOG) {
  105210. fallbacks.addFallback(0, "FOG");
  105211. }
  105212. if (defines.POINTSIZE) {
  105213. fallbacks.addFallback(1, "POINTSIZE");
  105214. }
  105215. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  105216. if (defines.NUM_BONE_INFLUENCERS > 0) {
  105217. fallbacks.addCPUSkinningFallback(0, mesh);
  105218. }
  105219. //Attributes
  105220. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105221. if (defines.NORMAL) {
  105222. attribs.push(BABYLON.VertexBuffer.NormalKind);
  105223. }
  105224. if (defines.UV1) {
  105225. attribs.push(BABYLON.VertexBuffer.UVKind);
  105226. }
  105227. if (defines.UV2) {
  105228. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105229. }
  105230. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  105231. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  105232. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  105233. "vFogInfos", "vFogColor", "pointSize",
  105234. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  105235. "vPrimaryColor", "vPrimaryColorShadow",
  105236. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  105237. "shadowLevel", "alpha",
  105238. "vBackgroundCenter", "vReflectionControl",
  105239. "vDiffuseInfos", "diffuseMatrix",
  105240. ];
  105241. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  105242. var uniformBuffers = ["Material", "Scene"];
  105243. if (BABYLON.ImageProcessingConfiguration) {
  105244. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  105245. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  105246. }
  105247. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  105248. uniformsNames: uniforms,
  105249. uniformBuffersNames: uniformBuffers,
  105250. samplers: samplers,
  105251. defines: defines,
  105252. maxSimultaneousLights: this._maxSimultaneousLights
  105253. });
  105254. var onCompiled = function (effect) {
  105255. if (_this.onCompiled) {
  105256. _this.onCompiled(effect);
  105257. }
  105258. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  105259. };
  105260. var join = defines.toString();
  105261. subMesh.setEffect(scene.getEngine().createEffect("background", {
  105262. attributes: attribs,
  105263. uniformsNames: uniforms,
  105264. uniformBuffersNames: uniformBuffers,
  105265. samplers: samplers,
  105266. defines: join,
  105267. fallbacks: fallbacks,
  105268. onCompiled: onCompiled,
  105269. onError: this.onError,
  105270. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  105271. }, engine), defines);
  105272. this.buildUniformLayout();
  105273. }
  105274. if (!subMesh.effect || !subMesh.effect.isReady()) {
  105275. return false;
  105276. }
  105277. defines._renderId = scene.getRenderId();
  105278. this._wasPreviouslyReady = true;
  105279. return true;
  105280. };
  105281. /**
  105282. * Compute the primary color according to the chosen perceptual color.
  105283. */
  105284. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  105285. if (!this.__perceptualColor) {
  105286. return;
  105287. }
  105288. this._primaryColor.copyFrom(this.__perceptualColor);
  105289. // Revert gamma space.
  105290. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  105291. // Revert image processing configuration.
  105292. if (this._imageProcessingConfiguration) {
  105293. // Revert Exposure.
  105294. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  105295. }
  105296. this._computePrimaryColors();
  105297. };
  105298. /**
  105299. * Compute the highlights and shadow colors according to their chosen levels.
  105300. */
  105301. BackgroundMaterial.prototype._computePrimaryColors = function () {
  105302. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  105303. return;
  105304. }
  105305. // Find the highlight color based on the configuration.
  105306. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  105307. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  105308. // Find the shadow color based on the configuration.
  105309. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  105310. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  105311. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  105312. };
  105313. /**
  105314. * Build the uniform buffer used in the material.
  105315. */
  105316. BackgroundMaterial.prototype.buildUniformLayout = function () {
  105317. // Order is important !
  105318. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  105319. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  105320. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  105321. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  105322. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  105323. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  105324. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  105325. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  105326. this._uniformBuffer.addUniform("pointSize", 1);
  105327. this._uniformBuffer.addUniform("shadowLevel", 1);
  105328. this._uniformBuffer.addUniform("alpha", 1);
  105329. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  105330. this._uniformBuffer.addUniform("vReflectionControl", 4);
  105331. this._uniformBuffer.create();
  105332. };
  105333. /**
  105334. * Unbind the material.
  105335. */
  105336. BackgroundMaterial.prototype.unbind = function () {
  105337. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  105338. this._uniformBuffer.setTexture("diffuseSampler", null);
  105339. }
  105340. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  105341. this._uniformBuffer.setTexture("reflectionSampler", null);
  105342. }
  105343. _super.prototype.unbind.call(this);
  105344. };
  105345. /**
  105346. * Bind only the world matrix to the material.
  105347. * @param world The world matrix to bind.
  105348. */
  105349. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  105350. this._activeEffect.setMatrix("world", world);
  105351. };
  105352. /**
  105353. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  105354. * @param world The world matrix to bind.
  105355. * @param subMesh The submesh to bind for.
  105356. */
  105357. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  105358. var scene = this.getScene();
  105359. var defines = subMesh._materialDefines;
  105360. if (!defines) {
  105361. return;
  105362. }
  105363. var effect = subMesh.effect;
  105364. if (!effect) {
  105365. return;
  105366. }
  105367. this._activeEffect = effect;
  105368. // Matrices
  105369. this.bindOnlyWorldMatrix(world);
  105370. // Bones
  105371. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  105372. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  105373. if (mustRebind) {
  105374. this._uniformBuffer.bindToEffect(effect, "Material");
  105375. this.bindViewProjection(effect);
  105376. var reflectionTexture = this._reflectionTexture;
  105377. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  105378. // Texture uniforms
  105379. if (scene.texturesEnabled) {
  105380. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105381. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  105382. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  105383. }
  105384. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105385. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  105386. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  105387. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  105388. }
  105389. }
  105390. if (this.shadowLevel > 0) {
  105391. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  105392. }
  105393. this._uniformBuffer.updateFloat("alpha", this.alpha);
  105394. // Point size
  105395. if (this.pointsCloud) {
  105396. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  105397. }
  105398. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  105399. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  105400. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  105401. }
  105402. else {
  105403. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  105404. }
  105405. }
  105406. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  105407. // Textures
  105408. if (scene.texturesEnabled) {
  105409. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105410. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  105411. }
  105412. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105413. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  105414. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105415. }
  105416. else if (!defines.REFLECTIONBLUR) {
  105417. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105418. }
  105419. else {
  105420. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  105421. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  105422. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  105423. }
  105424. if (defines.REFLECTIONFRESNEL) {
  105425. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  105426. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  105427. }
  105428. }
  105429. }
  105430. // Clip plane
  105431. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  105432. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  105433. }
  105434. if (mustRebind || !this.isFrozen) {
  105435. if (scene.lightsEnabled) {
  105436. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  105437. }
  105438. // View
  105439. this.bindView(effect);
  105440. // Fog
  105441. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  105442. // image processing
  105443. if (this._imageProcessingConfiguration) {
  105444. this._imageProcessingConfiguration.bind(this._activeEffect);
  105445. }
  105446. }
  105447. this._uniformBuffer.update();
  105448. this._afterBind(mesh, this._activeEffect);
  105449. };
  105450. /**
  105451. * Dispose the material.
  105452. * @param forceDisposeEffect Force disposal of the associated effect.
  105453. * @param forceDisposeTextures Force disposal of the associated textures.
  105454. */
  105455. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  105456. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  105457. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  105458. if (forceDisposeTextures) {
  105459. if (this.diffuseTexture) {
  105460. this.diffuseTexture.dispose();
  105461. }
  105462. if (this.reflectionTexture) {
  105463. this.reflectionTexture.dispose();
  105464. }
  105465. }
  105466. this._renderTargets.dispose();
  105467. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105468. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105469. }
  105470. _super.prototype.dispose.call(this, forceDisposeEffect);
  105471. };
  105472. /**
  105473. * Clones the material.
  105474. * @param name The cloned name.
  105475. * @returns The cloned material.
  105476. */
  105477. BackgroundMaterial.prototype.clone = function (name) {
  105478. var _this = this;
  105479. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  105480. };
  105481. /**
  105482. * Serializes the current material to its JSON representation.
  105483. * @returns The JSON representation.
  105484. */
  105485. BackgroundMaterial.prototype.serialize = function () {
  105486. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105487. serializationObject.customType = "BABYLON.BackgroundMaterial";
  105488. return serializationObject;
  105489. };
  105490. /**
  105491. * Gets the class name of the material
  105492. * @returns "BackgroundMaterial"
  105493. */
  105494. BackgroundMaterial.prototype.getClassName = function () {
  105495. return "BackgroundMaterial";
  105496. };
  105497. /**
  105498. * Parse a JSON input to create back a background material.
  105499. * @param source The JSON data to parse
  105500. * @param scene The scene to create the parsed material in
  105501. * @param rootUrl The root url of the assets the material depends upon
  105502. * @returns the instantiated BackgroundMaterial.
  105503. */
  105504. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  105505. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  105506. };
  105507. /**
  105508. * Standard reflectance value at parallel view angle.
  105509. */
  105510. BackgroundMaterial.StandardReflectance0 = 0.05;
  105511. /**
  105512. * Standard reflectance value at grazing angle.
  105513. */
  105514. BackgroundMaterial.StandardReflectance90 = 0.5;
  105515. __decorate([
  105516. BABYLON.serializeAsColor3()
  105517. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  105518. __decorate([
  105519. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105520. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  105521. __decorate([
  105522. BABYLON.serializeAsColor3()
  105523. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  105524. __decorate([
  105525. BABYLON.serialize()
  105526. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  105527. __decorate([
  105528. BABYLON.serialize()
  105529. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  105530. __decorate([
  105531. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105532. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  105533. __decorate([
  105534. BABYLON.serializeAsTexture()
  105535. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  105536. __decorate([
  105537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105538. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  105539. __decorate([
  105540. BABYLON.serialize()
  105541. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  105542. __decorate([
  105543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105544. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  105545. __decorate([
  105546. BABYLON.serializeAsTexture()
  105547. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  105548. __decorate([
  105549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105550. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  105551. __decorate([
  105552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105553. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  105554. __decorate([
  105555. BABYLON.serialize()
  105556. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  105557. __decorate([
  105558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105559. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  105560. __decorate([
  105561. BABYLON.serializeAsVector3()
  105562. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  105563. __decorate([
  105564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105565. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  105566. __decorate([
  105567. BABYLON.serialize()
  105568. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  105569. __decorate([
  105570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105571. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  105572. __decorate([
  105573. BABYLON.serialize()
  105574. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  105575. __decorate([
  105576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105577. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  105578. __decorate([
  105579. BABYLON.serialize()
  105580. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  105581. __decorate([
  105582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105583. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  105584. __decorate([
  105585. BABYLON.serialize()
  105586. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  105587. __decorate([
  105588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105589. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  105590. __decorate([
  105591. BABYLON.serialize()
  105592. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  105593. __decorate([
  105594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105595. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  105596. __decorate([
  105597. BABYLON.serialize()
  105598. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  105599. __decorate([
  105600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105601. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  105602. __decorate([
  105603. BABYLON.serialize()
  105604. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  105605. __decorate([
  105606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105607. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  105608. __decorate([
  105609. BABYLON.serialize()
  105610. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  105611. __decorate([
  105612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105613. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  105614. __decorate([
  105615. BABYLON.serialize()
  105616. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  105617. __decorate([
  105618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105619. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  105620. __decorate([
  105621. BABYLON.serializeAsImageProcessingConfiguration()
  105622. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  105623. return BackgroundMaterial;
  105624. }(BABYLON.PushMaterial));
  105625. BABYLON.BackgroundMaterial = BackgroundMaterial;
  105626. })(BABYLON || (BABYLON = {}));
  105627. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  105628. var __assign = (this && this.__assign) || function () {
  105629. __assign = Object.assign || function(t) {
  105630. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105631. s = arguments[i];
  105632. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105633. t[p] = s[p];
  105634. }
  105635. return t;
  105636. };
  105637. return __assign.apply(this, arguments);
  105638. };
  105639. var BABYLON;
  105640. (function (BABYLON) {
  105641. /**
  105642. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  105643. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  105644. * It also helps with the default setup of your imageProcessing configuration.
  105645. */
  105646. var EnvironmentHelper = /** @class */ (function () {
  105647. /**
  105648. * constructor
  105649. * @param options
  105650. * @param scene The scene to add the material to
  105651. */
  105652. function EnvironmentHelper(options, scene) {
  105653. var _this = this;
  105654. this._errorHandler = function (message, exception) {
  105655. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  105656. };
  105657. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  105658. this._scene = scene;
  105659. this.onErrorObservable = new BABYLON.Observable();
  105660. this._setupBackground();
  105661. this._setupImageProcessing();
  105662. }
  105663. /**
  105664. * Creates the default options for the helper.
  105665. */
  105666. EnvironmentHelper._getDefaultOptions = function () {
  105667. return {
  105668. createGround: true,
  105669. groundSize: 15,
  105670. groundTexture: this._groundTextureCDNUrl,
  105671. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  105672. groundOpacity: 0.9,
  105673. enableGroundShadow: true,
  105674. groundShadowLevel: 0.5,
  105675. enableGroundMirror: false,
  105676. groundMirrorSizeRatio: 0.3,
  105677. groundMirrorBlurKernel: 64,
  105678. groundMirrorAmount: 1,
  105679. groundMirrorFresnelWeight: 1,
  105680. groundMirrorFallOffDistance: 0,
  105681. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  105682. groundYBias: 0.00001,
  105683. createSkybox: true,
  105684. skyboxSize: 20,
  105685. skyboxTexture: this._skyboxTextureCDNUrl,
  105686. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  105687. backgroundYRotation: 0,
  105688. sizeAuto: true,
  105689. rootPosition: BABYLON.Vector3.Zero(),
  105690. setupImageProcessing: true,
  105691. environmentTexture: this._environmentTextureCDNUrl,
  105692. cameraExposure: 0.8,
  105693. cameraContrast: 1.2,
  105694. toneMappingEnabled: true,
  105695. };
  105696. };
  105697. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  105698. /**
  105699. * Gets the root mesh created by the helper.
  105700. */
  105701. get: function () {
  105702. return this._rootMesh;
  105703. },
  105704. enumerable: true,
  105705. configurable: true
  105706. });
  105707. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  105708. /**
  105709. * Gets the skybox created by the helper.
  105710. */
  105711. get: function () {
  105712. return this._skybox;
  105713. },
  105714. enumerable: true,
  105715. configurable: true
  105716. });
  105717. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  105718. /**
  105719. * Gets the skybox texture created by the helper.
  105720. */
  105721. get: function () {
  105722. return this._skyboxTexture;
  105723. },
  105724. enumerable: true,
  105725. configurable: true
  105726. });
  105727. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  105728. /**
  105729. * Gets the skybox material created by the helper.
  105730. */
  105731. get: function () {
  105732. return this._skyboxMaterial;
  105733. },
  105734. enumerable: true,
  105735. configurable: true
  105736. });
  105737. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  105738. /**
  105739. * Gets the ground mesh created by the helper.
  105740. */
  105741. get: function () {
  105742. return this._ground;
  105743. },
  105744. enumerable: true,
  105745. configurable: true
  105746. });
  105747. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  105748. /**
  105749. * Gets the ground texture created by the helper.
  105750. */
  105751. get: function () {
  105752. return this._groundTexture;
  105753. },
  105754. enumerable: true,
  105755. configurable: true
  105756. });
  105757. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  105758. /**
  105759. * Gets the ground mirror created by the helper.
  105760. */
  105761. get: function () {
  105762. return this._groundMirror;
  105763. },
  105764. enumerable: true,
  105765. configurable: true
  105766. });
  105767. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  105768. /**
  105769. * Gets the ground mirror render list to helps pushing the meshes
  105770. * you wish in the ground reflection.
  105771. */
  105772. get: function () {
  105773. if (this._groundMirror) {
  105774. return this._groundMirror.renderList;
  105775. }
  105776. return null;
  105777. },
  105778. enumerable: true,
  105779. configurable: true
  105780. });
  105781. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  105782. /**
  105783. * Gets the ground material created by the helper.
  105784. */
  105785. get: function () {
  105786. return this._groundMaterial;
  105787. },
  105788. enumerable: true,
  105789. configurable: true
  105790. });
  105791. /**
  105792. * Updates the background according to the new options
  105793. * @param options
  105794. */
  105795. EnvironmentHelper.prototype.updateOptions = function (options) {
  105796. var newOptions = __assign({}, this._options, options);
  105797. if (this._ground && !newOptions.createGround) {
  105798. this._ground.dispose();
  105799. this._ground = null;
  105800. }
  105801. if (this._groundMaterial && !newOptions.createGround) {
  105802. this._groundMaterial.dispose();
  105803. this._groundMaterial = null;
  105804. }
  105805. if (this._groundTexture) {
  105806. if (this._options.groundTexture != newOptions.groundTexture) {
  105807. this._groundTexture.dispose();
  105808. this._groundTexture = null;
  105809. }
  105810. }
  105811. if (this._skybox && !newOptions.createSkybox) {
  105812. this._skybox.dispose();
  105813. this._skybox = null;
  105814. }
  105815. if (this._skyboxMaterial && !newOptions.createSkybox) {
  105816. this._skyboxMaterial.dispose();
  105817. this._skyboxMaterial = null;
  105818. }
  105819. if (this._skyboxTexture) {
  105820. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  105821. this._skyboxTexture.dispose();
  105822. this._skyboxTexture = null;
  105823. }
  105824. }
  105825. if (this._groundMirror && !newOptions.enableGroundMirror) {
  105826. this._groundMirror.dispose();
  105827. this._groundMirror = null;
  105828. }
  105829. if (this._scene.environmentTexture) {
  105830. if (this._options.environmentTexture != newOptions.environmentTexture) {
  105831. this._scene.environmentTexture.dispose();
  105832. }
  105833. }
  105834. this._options = newOptions;
  105835. this._setupBackground();
  105836. this._setupImageProcessing();
  105837. };
  105838. /**
  105839. * Sets the primary color of all the available elements.
  105840. * @param color the main color to affect to the ground and the background
  105841. */
  105842. EnvironmentHelper.prototype.setMainColor = function (color) {
  105843. if (this.groundMaterial) {
  105844. this.groundMaterial.primaryColor = color;
  105845. }
  105846. if (this.skyboxMaterial) {
  105847. this.skyboxMaterial.primaryColor = color;
  105848. }
  105849. if (this.groundMirror) {
  105850. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  105851. }
  105852. };
  105853. /**
  105854. * Setup the image processing according to the specified options.
  105855. */
  105856. EnvironmentHelper.prototype._setupImageProcessing = function () {
  105857. if (this._options.setupImageProcessing) {
  105858. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  105859. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  105860. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  105861. this._setupEnvironmentTexture();
  105862. }
  105863. };
  105864. /**
  105865. * Setup the environment texture according to the specified options.
  105866. */
  105867. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  105868. if (this._scene.environmentTexture) {
  105869. return;
  105870. }
  105871. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  105872. this._scene.environmentTexture = this._options.environmentTexture;
  105873. return;
  105874. }
  105875. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  105876. this._scene.environmentTexture = environmentTexture;
  105877. };
  105878. /**
  105879. * Setup the background according to the specified options.
  105880. */
  105881. EnvironmentHelper.prototype._setupBackground = function () {
  105882. if (!this._rootMesh) {
  105883. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  105884. }
  105885. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  105886. var sceneSize = this._getSceneSize();
  105887. if (this._options.createGround) {
  105888. this._setupGround(sceneSize);
  105889. this._setupGroundMaterial();
  105890. this._setupGroundDiffuseTexture();
  105891. if (this._options.enableGroundMirror) {
  105892. this._setupGroundMirrorTexture(sceneSize);
  105893. }
  105894. this._setupMirrorInGroundMaterial();
  105895. }
  105896. if (this._options.createSkybox) {
  105897. this._setupSkybox(sceneSize);
  105898. this._setupSkyboxMaterial();
  105899. this._setupSkyboxReflectionTexture();
  105900. }
  105901. this._rootMesh.position.x = sceneSize.rootPosition.x;
  105902. this._rootMesh.position.z = sceneSize.rootPosition.z;
  105903. this._rootMesh.position.y = sceneSize.rootPosition.y;
  105904. };
  105905. /**
  105906. * Get the scene sizes according to the setup.
  105907. */
  105908. EnvironmentHelper.prototype._getSceneSize = function () {
  105909. var _this = this;
  105910. var groundSize = this._options.groundSize;
  105911. var skyboxSize = this._options.skyboxSize;
  105912. var rootPosition = this._options.rootPosition;
  105913. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  105914. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  105915. }
  105916. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  105917. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  105918. });
  105919. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  105920. if (this._options.sizeAuto) {
  105921. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  105922. this._scene.activeCamera.upperRadiusLimit) {
  105923. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  105924. skyboxSize = groundSize;
  105925. }
  105926. var sceneDiagonalLenght = sceneDiagonal.length();
  105927. if (sceneDiagonalLenght > groundSize) {
  105928. groundSize = sceneDiagonalLenght * 2;
  105929. skyboxSize = groundSize;
  105930. }
  105931. // 10 % bigger.
  105932. groundSize *= 1.1;
  105933. skyboxSize *= 1.5;
  105934. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  105935. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  105936. }
  105937. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  105938. };
  105939. /**
  105940. * Setup the ground according to the specified options.
  105941. */
  105942. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  105943. var _this = this;
  105944. if (!this._ground || this._ground.isDisposed()) {
  105945. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  105946. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  105947. this._ground.parent = this._rootMesh;
  105948. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  105949. }
  105950. this._ground.receiveShadows = this._options.enableGroundShadow;
  105951. };
  105952. /**
  105953. * Setup the ground material according to the specified options.
  105954. */
  105955. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  105956. if (!this._groundMaterial) {
  105957. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  105958. }
  105959. this._groundMaterial.alpha = this._options.groundOpacity;
  105960. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  105961. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  105962. this._groundMaterial.primaryColor = this._options.groundColor;
  105963. this._groundMaterial.useRGBColor = false;
  105964. this._groundMaterial.enableNoise = true;
  105965. if (this._ground) {
  105966. this._ground.material = this._groundMaterial;
  105967. }
  105968. };
  105969. /**
  105970. * Setup the ground diffuse texture according to the specified options.
  105971. */
  105972. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  105973. if (!this._groundMaterial) {
  105974. return;
  105975. }
  105976. if (this._groundTexture) {
  105977. return;
  105978. }
  105979. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  105980. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  105981. return;
  105982. }
  105983. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  105984. diffuseTexture.gammaSpace = false;
  105985. diffuseTexture.hasAlpha = true;
  105986. this._groundMaterial.diffuseTexture = diffuseTexture;
  105987. };
  105988. /**
  105989. * Setup the ground mirror texture according to the specified options.
  105990. */
  105991. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  105992. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105993. if (!this._groundMirror) {
  105994. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  105995. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  105996. this._groundMirror.anisotropicFilteringLevel = 1;
  105997. this._groundMirror.wrapU = wrapping;
  105998. this._groundMirror.wrapV = wrapping;
  105999. this._groundMirror.gammaSpace = false;
  106000. if (this._groundMirror.renderList) {
  106001. for (var i = 0; i < this._scene.meshes.length; i++) {
  106002. var mesh = this._scene.meshes[i];
  106003. if (mesh !== this._ground &&
  106004. mesh !== this._skybox &&
  106005. mesh !== this._rootMesh) {
  106006. this._groundMirror.renderList.push(mesh);
  106007. }
  106008. }
  106009. }
  106010. }
  106011. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  106012. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  106013. };
  106014. /**
  106015. * Setup the ground to receive the mirror texture.
  106016. */
  106017. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  106018. if (this._groundMaterial) {
  106019. this._groundMaterial.reflectionTexture = this._groundMirror;
  106020. this._groundMaterial.reflectionFresnel = true;
  106021. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  106022. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  106023. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  106024. }
  106025. };
  106026. /**
  106027. * Setup the skybox according to the specified options.
  106028. */
  106029. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  106030. var _this = this;
  106031. if (!this._skybox || this._skybox.isDisposed()) {
  106032. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  106033. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  106034. }
  106035. this._skybox.parent = this._rootMesh;
  106036. };
  106037. /**
  106038. * Setup the skybox material according to the specified options.
  106039. */
  106040. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  106041. if (!this._skybox) {
  106042. return;
  106043. }
  106044. if (!this._skyboxMaterial) {
  106045. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  106046. }
  106047. this._skyboxMaterial.useRGBColor = false;
  106048. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  106049. this._skyboxMaterial.enableNoise = true;
  106050. this._skybox.material = this._skyboxMaterial;
  106051. };
  106052. /**
  106053. * Setup the skybox reflection texture according to the specified options.
  106054. */
  106055. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  106056. if (!this._skyboxMaterial) {
  106057. return;
  106058. }
  106059. if (this._skyboxTexture) {
  106060. return;
  106061. }
  106062. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  106063. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  106064. return;
  106065. }
  106066. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106067. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  106068. this._skyboxTexture.gammaSpace = false;
  106069. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  106070. };
  106071. /**
  106072. * Dispose all the elements created by the Helper.
  106073. */
  106074. EnvironmentHelper.prototype.dispose = function () {
  106075. if (this._groundMaterial) {
  106076. this._groundMaterial.dispose(true, true);
  106077. }
  106078. if (this._skyboxMaterial) {
  106079. this._skyboxMaterial.dispose(true, true);
  106080. }
  106081. this._rootMesh.dispose(false);
  106082. };
  106083. /**
  106084. * Default ground texture URL.
  106085. */
  106086. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  106087. /**
  106088. * Default skybox texture URL.
  106089. */
  106090. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  106091. /**
  106092. * Default environment texture URL.
  106093. */
  106094. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  106095. return EnvironmentHelper;
  106096. }());
  106097. BABYLON.EnvironmentHelper = EnvironmentHelper;
  106098. })(BABYLON || (BABYLON = {}));
  106099. //# sourceMappingURL=babylon.environmentHelper.js.map
  106100. var BABYLON;
  106101. (function (BABYLON) {
  106102. /** Internal class used to store shapes for emitters */
  106103. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  106104. function ParticleSystemSetEmitterCreationOptions() {
  106105. }
  106106. return ParticleSystemSetEmitterCreationOptions;
  106107. }());
  106108. /**
  106109. * Represents a set of particle systems working together to create a specific effect
  106110. */
  106111. var ParticleSystemSet = /** @class */ (function () {
  106112. function ParticleSystemSet() {
  106113. /**
  106114. * Gets the particle system list
  106115. */
  106116. this.systems = new Array();
  106117. }
  106118. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  106119. /**
  106120. * Gets the emitter node used with this set
  106121. */
  106122. get: function () {
  106123. return this._emitterNode;
  106124. },
  106125. enumerable: true,
  106126. configurable: true
  106127. });
  106128. /**
  106129. * Creates a new emitter mesh as a sphere
  106130. * @param options defines the options used to create the sphere
  106131. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  106132. * @param scene defines the hosting scene
  106133. */
  106134. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  106135. if (this._emitterNode) {
  106136. this._emitterNode.dispose();
  106137. }
  106138. this._emitterCreationOptions = {
  106139. kind: "Sphere",
  106140. options: options,
  106141. renderingGroupId: renderingGroupId
  106142. };
  106143. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  106144. emitterMesh.renderingGroupId = renderingGroupId;
  106145. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  106146. material.emissiveColor = options.color;
  106147. emitterMesh.material = material;
  106148. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106149. var system = _a[_i];
  106150. system.emitter = emitterMesh;
  106151. }
  106152. this._emitterNode = emitterMesh;
  106153. };
  106154. /**
  106155. * Starts all particle systems of the set
  106156. * @param emitter defines an optional mesh to use as emitter for the particle systems
  106157. */
  106158. ParticleSystemSet.prototype.start = function (emitter) {
  106159. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106160. var system = _a[_i];
  106161. if (emitter) {
  106162. system.emitter = emitter;
  106163. }
  106164. system.start();
  106165. }
  106166. };
  106167. /**
  106168. * Release all associated resources
  106169. */
  106170. ParticleSystemSet.prototype.dispose = function () {
  106171. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106172. var system = _a[_i];
  106173. system.dispose();
  106174. }
  106175. this.systems = [];
  106176. if (this._emitterNode) {
  106177. this._emitterNode.dispose();
  106178. this._emitterNode = null;
  106179. }
  106180. };
  106181. /**
  106182. * Serialize the set into a JSON compatible object
  106183. * @returns a JSON compatible representation of the set
  106184. */
  106185. ParticleSystemSet.prototype.serialize = function () {
  106186. var result = {};
  106187. result.systems = [];
  106188. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106189. var system = _a[_i];
  106190. result.systems.push(system.serialize());
  106191. }
  106192. if (this._emitterNode) {
  106193. result.emitter = this._emitterCreationOptions;
  106194. }
  106195. return result;
  106196. };
  106197. /**
  106198. * Parse a new ParticleSystemSet from a serialized source
  106199. * @param data defines a JSON compatible representation of the set
  106200. * @param scene defines the hosting scene
  106201. * @param gpu defines if we want GPU particles or CPU particles
  106202. * @returns a new ParticleSystemSet
  106203. */
  106204. ParticleSystemSet.Parse = function (data, scene, gpu) {
  106205. if (gpu === void 0) { gpu = false; }
  106206. var result = new ParticleSystemSet();
  106207. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  106208. scene = scene || BABYLON.Engine.LastCreatedScene;
  106209. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  106210. var system = _a[_i];
  106211. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  106212. }
  106213. if (data.emitter) {
  106214. var options = data.emitter.options;
  106215. switch (data.emitter.kind) {
  106216. case "Sphere":
  106217. result.setEmitterAsSphere({
  106218. diameter: options.diameter,
  106219. segments: options.segments,
  106220. color: BABYLON.Color3.FromArray(options.color)
  106221. }, data.emitter.renderingGroupId, scene);
  106222. break;
  106223. }
  106224. }
  106225. return result;
  106226. };
  106227. return ParticleSystemSet;
  106228. }());
  106229. BABYLON.ParticleSystemSet = ParticleSystemSet;
  106230. })(BABYLON || (BABYLON = {}));
  106231. //# sourceMappingURL=babylon.particleSystemSet.js.map
  106232. var BABYLON;
  106233. (function (BABYLON) {
  106234. /**
  106235. * This class is made for on one-liner static method to help creating particle system set.
  106236. */
  106237. var ParticleHelper = /** @class */ (function () {
  106238. function ParticleHelper() {
  106239. }
  106240. /**
  106241. * Create a default particle system that you can tweak
  106242. * @param emitter defines the emitter to use
  106243. * @param capacity defines the system capacity (default is 500 particles)
  106244. * @param scene defines the hosting scene
  106245. * @returns the new Particle system
  106246. */
  106247. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  106248. if (capacity === void 0) { capacity = 500; }
  106249. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  106250. system.emitter = emitter;
  106251. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  106252. system.createConeEmitter(0.1, Math.PI / 4);
  106253. // Particle color
  106254. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106255. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106256. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  106257. // Particle Size
  106258. system.minSize = 0.1;
  106259. system.maxSize = 0.1;
  106260. // Emission speed
  106261. system.minEmitPower = 2;
  106262. system.maxEmitPower = 2;
  106263. // Update speed
  106264. system.updateSpeed = 1 / 60;
  106265. system.emitRate = 30;
  106266. return system;
  106267. };
  106268. /**
  106269. * This is the main static method (one-liner) of this helper to create different particle systems
  106270. * @param type This string represents the type to the particle system to create
  106271. * @param scene The scene where the particle system should live
  106272. * @param gpu If the system will use gpu
  106273. * @returns the ParticleSystemSet created
  106274. */
  106275. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  106276. if (gpu === void 0) { gpu = false; }
  106277. if (!scene) {
  106278. scene = BABYLON.Engine.LastCreatedScene;
  106279. ;
  106280. }
  106281. var token = {};
  106282. scene._addPendingData(token);
  106283. return new Promise(function (resolve, reject) {
  106284. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  106285. scene._removePendingData(token);
  106286. return reject("Particle system with GPU is not supported.");
  106287. }
  106288. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  106289. scene._removePendingData(token);
  106290. var newData = JSON.parse(data.toString());
  106291. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  106292. }, undefined, undefined, undefined, function (req, exception) {
  106293. scene._removePendingData(token);
  106294. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  106295. });
  106296. });
  106297. };
  106298. /**
  106299. * Static function used to export a particle system to a ParticleSystemSet variable.
  106300. * Please note that the emitter shape is not exported
  106301. * @param system defines the particle systems to export
  106302. */
  106303. ParticleHelper.ExportSet = function (systems) {
  106304. var set = new BABYLON.ParticleSystemSet();
  106305. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  106306. var system = systems_1[_i];
  106307. set.systems.push(system);
  106308. }
  106309. return set;
  106310. };
  106311. /**
  106312. * Gets or sets base Assets URL
  106313. */
  106314. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  106315. return ParticleHelper;
  106316. }());
  106317. BABYLON.ParticleHelper = ParticleHelper;
  106318. })(BABYLON || (BABYLON = {}));
  106319. //# sourceMappingURL=babylon.particleHelper.js.map
  106320. var BABYLON;
  106321. (function (BABYLON) {
  106322. /**
  106323. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  106324. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  106325. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  106326. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106327. */
  106328. var VideoDome = /** @class */ (function (_super) {
  106329. __extends(VideoDome, _super);
  106330. /**
  106331. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  106332. * @param name Element's name, child elements will append suffixes for their own names.
  106333. * @param urlsOrVideo defines the url(s) or the video element to use
  106334. * @param options An object containing optional or exposed sub element properties
  106335. */
  106336. function VideoDome(name, urlsOrVideo, options, scene) {
  106337. var _this = _super.call(this, name, scene) || this;
  106338. _this._useDirectMapping = false;
  106339. // set defaults and manage values
  106340. name = name || "videoDome";
  106341. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106342. options.clickToPlay = Boolean(options.clickToPlay);
  106343. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  106344. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  106345. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106346. if (options.useDirectMapping === undefined) {
  106347. _this._useDirectMapping = true;
  106348. }
  106349. else {
  106350. _this._useDirectMapping = options.useDirectMapping;
  106351. }
  106352. _this._setReady(false);
  106353. // create
  106354. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  106355. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106356. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  106357. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106358. texture.onLoadObservable.addOnce(function () {
  106359. _this._setReady(true);
  106360. });
  106361. // configure material
  106362. material.useEquirectangularFOV = true;
  106363. material.fovMultiplier = 1.0;
  106364. material.opacityFresnel = false;
  106365. if (_this._useDirectMapping) {
  106366. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106367. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106368. material.diffuseTexture = texture;
  106369. }
  106370. else {
  106371. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106372. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106373. material.reflectionTexture = texture;
  106374. }
  106375. // configure mesh
  106376. _this._mesh.material = material;
  106377. _this._mesh.parent = _this;
  106378. // optional configuration
  106379. if (options.clickToPlay) {
  106380. scene.onPointerUp = function () {
  106381. _this._videoTexture.video.play();
  106382. };
  106383. }
  106384. return _this;
  106385. }
  106386. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  106387. /**
  106388. * Gets the video texture being displayed on the sphere
  106389. */
  106390. get: function () {
  106391. return this._videoTexture;
  106392. },
  106393. enumerable: true,
  106394. configurable: true
  106395. });
  106396. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  106397. /**
  106398. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106399. * Also see the options.resolution property.
  106400. */
  106401. get: function () {
  106402. return this._material.fovMultiplier;
  106403. },
  106404. set: function (value) {
  106405. this._material.fovMultiplier = value;
  106406. },
  106407. enumerable: true,
  106408. configurable: true
  106409. });
  106410. /**
  106411. * Releases resources associated with this node.
  106412. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106413. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106414. */
  106415. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106416. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106417. this._videoTexture.dispose();
  106418. this._mesh.dispose();
  106419. this._material.dispose();
  106420. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106421. };
  106422. return VideoDome;
  106423. }(BABYLON.TransformNode));
  106424. BABYLON.VideoDome = VideoDome;
  106425. })(BABYLON || (BABYLON = {}));
  106426. //# sourceMappingURL=babylon.videoDome.js.map
  106427. var BABYLON;
  106428. (function (BABYLON) {
  106429. /**
  106430. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  106431. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  106432. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  106433. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106434. */
  106435. var PhotoDome = /** @class */ (function (_super) {
  106436. __extends(PhotoDome, _super);
  106437. /**
  106438. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  106439. * @param name Element's name, child elements will append suffixes for their own names.
  106440. * @param urlsOfPhoto defines the url of the photo to display
  106441. * @param options defines an object containing optional or exposed sub element properties
  106442. * @param onError defines a callback called when an error occured while loading the texture
  106443. */
  106444. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  106445. if (onError === void 0) { onError = null; }
  106446. var _this = _super.call(this, name, scene) || this;
  106447. _this._useDirectMapping = false;
  106448. /**
  106449. * Observable raised when an error occured while loading the 360 image
  106450. */
  106451. _this.onLoadErrorObservable = new BABYLON.Observable();
  106452. // set defaults and manage values
  106453. name = name || "photoDome";
  106454. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106455. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106456. if (options.useDirectMapping === undefined) {
  106457. _this._useDirectMapping = true;
  106458. }
  106459. else {
  106460. _this._useDirectMapping = options.useDirectMapping;
  106461. }
  106462. _this._setReady(false);
  106463. // create
  106464. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106465. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106466. // configure material
  106467. material.opacityFresnel = false;
  106468. material.useEquirectangularFOV = true;
  106469. material.fovMultiplier = 1.0;
  106470. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  106471. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  106472. if (onError) {
  106473. onError(message, exception);
  106474. }
  106475. });
  106476. _this.photoTexture.onLoadObservable.addOnce(function () {
  106477. _this._setReady(true);
  106478. });
  106479. // configure mesh
  106480. _this._mesh.material = material;
  106481. _this._mesh.parent = _this;
  106482. return _this;
  106483. }
  106484. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  106485. /**
  106486. * Gets or sets the texture being displayed on the sphere
  106487. */
  106488. get: function () {
  106489. return this._photoTexture;
  106490. },
  106491. set: function (value) {
  106492. if (this._photoTexture === value) {
  106493. return;
  106494. }
  106495. this._photoTexture = value;
  106496. if (this._useDirectMapping) {
  106497. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106498. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106499. this._material.diffuseTexture = this._photoTexture;
  106500. }
  106501. else {
  106502. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106503. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106504. this._material.reflectionTexture = this._photoTexture;
  106505. }
  106506. },
  106507. enumerable: true,
  106508. configurable: true
  106509. });
  106510. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  106511. /**
  106512. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106513. * Also see the options.resolution property.
  106514. */
  106515. get: function () {
  106516. return this._material.fovMultiplier;
  106517. },
  106518. set: function (value) {
  106519. this._material.fovMultiplier = value;
  106520. },
  106521. enumerable: true,
  106522. configurable: true
  106523. });
  106524. /**
  106525. * Releases resources associated with this node.
  106526. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106527. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106528. */
  106529. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106530. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106531. this._photoTexture.dispose();
  106532. this._mesh.dispose();
  106533. this._material.dispose();
  106534. this.onLoadErrorObservable.clear();
  106535. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106536. };
  106537. return PhotoDome;
  106538. }(BABYLON.TransformNode));
  106539. BABYLON.PhotoDome = PhotoDome;
  106540. })(BABYLON || (BABYLON = {}));
  106541. //# sourceMappingURL=babylon.photoDome.js.map
  106542. var BABYLON;
  106543. (function (BABYLON) {
  106544. BABYLON.Engine.prototype.createQuery = function () {
  106545. return this._gl.createQuery();
  106546. };
  106547. BABYLON.Engine.prototype.deleteQuery = function (query) {
  106548. this._gl.deleteQuery(query);
  106549. return this;
  106550. };
  106551. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  106552. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  106553. };
  106554. BABYLON.Engine.prototype.getQueryResult = function (query) {
  106555. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  106556. };
  106557. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  106558. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  106559. this._gl.beginQuery(glAlgorithm, query);
  106560. return this;
  106561. };
  106562. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  106563. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  106564. this._gl.endQuery(glAlgorithm);
  106565. return this;
  106566. };
  106567. BABYLON.Engine.prototype._createTimeQuery = function () {
  106568. var timerQuery = this.getCaps().timerQuery;
  106569. if (timerQuery.createQueryEXT) {
  106570. return timerQuery.createQueryEXT();
  106571. }
  106572. return this.createQuery();
  106573. };
  106574. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  106575. var timerQuery = this.getCaps().timerQuery;
  106576. if (timerQuery.deleteQueryEXT) {
  106577. timerQuery.deleteQueryEXT(query);
  106578. return;
  106579. }
  106580. this.deleteQuery(query);
  106581. };
  106582. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  106583. var timerQuery = this.getCaps().timerQuery;
  106584. if (timerQuery.getQueryObjectEXT) {
  106585. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  106586. }
  106587. return this.getQueryResult(query);
  106588. };
  106589. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  106590. var timerQuery = this.getCaps().timerQuery;
  106591. if (timerQuery.getQueryObjectEXT) {
  106592. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  106593. }
  106594. return this.isQueryResultAvailable(query);
  106595. };
  106596. BABYLON.Engine.prototype.startTimeQuery = function () {
  106597. var caps = this.getCaps();
  106598. var timerQuery = caps.timerQuery;
  106599. if (!timerQuery) {
  106600. return null;
  106601. }
  106602. var token = new BABYLON._TimeToken();
  106603. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  106604. if (caps.canUseTimestampForTimerQuery) {
  106605. token._startTimeQuery = this._createTimeQuery();
  106606. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  106607. }
  106608. else {
  106609. if (this._currentNonTimestampToken) {
  106610. return this._currentNonTimestampToken;
  106611. }
  106612. token._timeElapsedQuery = this._createTimeQuery();
  106613. if (timerQuery.beginQueryEXT) {
  106614. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  106615. }
  106616. else {
  106617. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  106618. }
  106619. this._currentNonTimestampToken = token;
  106620. }
  106621. return token;
  106622. };
  106623. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  106624. var caps = this.getCaps();
  106625. var timerQuery = caps.timerQuery;
  106626. if (!timerQuery || !token) {
  106627. return -1;
  106628. }
  106629. if (caps.canUseTimestampForTimerQuery) {
  106630. if (!token._startTimeQuery) {
  106631. return -1;
  106632. }
  106633. if (!token._endTimeQuery) {
  106634. token._endTimeQuery = this._createTimeQuery();
  106635. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  106636. }
  106637. }
  106638. else if (!token._timeElapsedQueryEnded) {
  106639. if (!token._timeElapsedQuery) {
  106640. return -1;
  106641. }
  106642. if (timerQuery.endQueryEXT) {
  106643. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  106644. }
  106645. else {
  106646. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  106647. }
  106648. token._timeElapsedQueryEnded = true;
  106649. }
  106650. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  106651. var available = false;
  106652. if (token._endTimeQuery) {
  106653. available = this._getTimeQueryAvailability(token._endTimeQuery);
  106654. }
  106655. else if (token._timeElapsedQuery) {
  106656. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  106657. }
  106658. if (available && !disjoint) {
  106659. var result = 0;
  106660. if (caps.canUseTimestampForTimerQuery) {
  106661. if (!token._startTimeQuery || !token._endTimeQuery) {
  106662. return -1;
  106663. }
  106664. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  106665. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  106666. result = timeEnd - timeStart;
  106667. this._deleteTimeQuery(token._startTimeQuery);
  106668. this._deleteTimeQuery(token._endTimeQuery);
  106669. token._startTimeQuery = null;
  106670. token._endTimeQuery = null;
  106671. }
  106672. else {
  106673. if (!token._timeElapsedQuery) {
  106674. return -1;
  106675. }
  106676. result = this._getTimeQueryResult(token._timeElapsedQuery);
  106677. this._deleteTimeQuery(token._timeElapsedQuery);
  106678. token._timeElapsedQuery = null;
  106679. token._timeElapsedQueryEnded = false;
  106680. this._currentNonTimestampToken = null;
  106681. }
  106682. return result;
  106683. }
  106684. return -1;
  106685. };
  106686. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  106687. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  106688. };
  106689. // We also need to update AbstractMesh as there is a portion of the code there
  106690. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  106691. var engine = this.getEngine();
  106692. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  106693. this._isOccluded = false;
  106694. return;
  106695. }
  106696. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  106697. this._isOccluded = false;
  106698. return;
  106699. }
  106700. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  106701. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  106702. if (isOcclusionQueryAvailable) {
  106703. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  106704. this._isOcclusionQueryInProgress = false;
  106705. this._occlusionInternalRetryCounter = 0;
  106706. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  106707. }
  106708. else {
  106709. this._occlusionInternalRetryCounter++;
  106710. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  106711. this._isOcclusionQueryInProgress = false;
  106712. this._occlusionInternalRetryCounter = 0;
  106713. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  106714. // if strict continue the last state of the object.
  106715. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  106716. }
  106717. else {
  106718. return;
  106719. }
  106720. }
  106721. }
  106722. var scene = this.getScene();
  106723. if (scene.getBoundingBoxRenderer) {
  106724. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  106725. if (!this._occlusionQuery) {
  106726. this._occlusionQuery = engine.createQuery();
  106727. }
  106728. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  106729. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  106730. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  106731. this._isOcclusionQueryInProgress = true;
  106732. }
  106733. };
  106734. })(BABYLON || (BABYLON = {}));
  106735. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  106736. var BABYLON;
  106737. (function (BABYLON) {
  106738. /**
  106739. * Class used to generate noise procedural textures
  106740. */
  106741. var NoiseProceduralTexture = /** @class */ (function (_super) {
  106742. __extends(NoiseProceduralTexture, _super);
  106743. /**
  106744. * Creates a new NoiseProceduralTexture
  106745. * @param name defines the name fo the texture
  106746. * @param size defines the size of the texture (default is 256)
  106747. * @param scene defines the hosting scene
  106748. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  106749. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  106750. */
  106751. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  106752. if (size === void 0) { size = 256; }
  106753. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  106754. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  106755. _this._time = 0;
  106756. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  106757. _this.brightness = 0.2;
  106758. /** Defines the number of octaves to process */
  106759. _this.octaves = 3;
  106760. /** Defines the level of persistence (0.8 by default) */
  106761. _this.persistence = 0.8;
  106762. /** Gets or sets animation speed factor (default is 1) */
  106763. _this.animationSpeedFactor = 1;
  106764. _this._updateShaderUniforms();
  106765. return _this;
  106766. }
  106767. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  106768. var scene = this.getScene();
  106769. if (!scene) {
  106770. return;
  106771. }
  106772. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  106773. this.setFloat("brightness", this.brightness);
  106774. this.setInt("octaves", this.octaves);
  106775. this.setFloat("persistence", this.persistence);
  106776. this.setFloat("timeScale", this._time);
  106777. };
  106778. /** Generate the current state of the procedural texture */
  106779. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  106780. this._updateShaderUniforms();
  106781. _super.prototype.render.call(this, useCameraPostProcess);
  106782. };
  106783. /**
  106784. * Serializes this noise procedural texture
  106785. * @returns a serialized noise procedural texture object
  106786. */
  106787. NoiseProceduralTexture.prototype.serialize = function () {
  106788. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  106789. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  106790. return serializationObject;
  106791. };
  106792. /**
  106793. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  106794. * @param parsedTexture defines parsed texture data
  106795. * @param scene defines the current scene
  106796. * @param rootUrl defines the root URL containing noise procedural texture information
  106797. * @returns a parsed NoiseProceduralTexture
  106798. */
  106799. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  106800. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  106801. return texture;
  106802. };
  106803. return NoiseProceduralTexture;
  106804. }(BABYLON.ProceduralTexture));
  106805. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  106806. })(BABYLON || (BABYLON = {}));
  106807. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  106808. var __assign = (this && this.__assign) || function () {
  106809. __assign = Object.assign || function(t) {
  106810. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106811. s = arguments[i];
  106812. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106813. t[p] = s[p];
  106814. }
  106815. return t;
  106816. };
  106817. return __assign.apply(this, arguments);
  106818. };
  106819. var BABYLON;
  106820. (function (BABYLON) {
  106821. /**
  106822. * This can helps recording videos from BabylonJS.
  106823. * This is based on the available WebRTC functionalities of the browser.
  106824. *
  106825. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  106826. */
  106827. var VideoRecorder = /** @class */ (function () {
  106828. /**
  106829. * Create a new VideoCapture object which can help converting what you see in Babylon to
  106830. * a video file.
  106831. * @param engine Defines the BabylonJS Engine you wish to record
  106832. * @param options Defines options that can be used to customized the capture
  106833. */
  106834. function VideoRecorder(engine, options) {
  106835. if (options === void 0) { options = null; }
  106836. if (!VideoRecorder.IsSupported(engine)) {
  106837. throw "Your browser does not support recording so far.";
  106838. }
  106839. var canvas = engine.getRenderingCanvas();
  106840. if (!canvas) {
  106841. throw "The babylon engine must have a canvas to be recorded";
  106842. }
  106843. this._canvas = canvas;
  106844. this._canvas.isRecording = false;
  106845. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  106846. var stream = this._canvas.captureStream(this._options.fps);
  106847. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  106848. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  106849. this._mediaRecorder.onerror = this._handleError.bind(this);
  106850. this._mediaRecorder.onstop = this._handleStop.bind(this);
  106851. }
  106852. /**
  106853. * Returns wehther or not the VideoRecorder is available in your browser.
  106854. * @param engine Defines the Babylon Engine to check the support for
  106855. * @returns true if supported otherwise false
  106856. */
  106857. VideoRecorder.IsSupported = function (engine) {
  106858. var canvas = engine.getRenderingCanvas();
  106859. return (!!canvas && typeof canvas.captureStream === "function");
  106860. };
  106861. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  106862. /**
  106863. * True wether a recording is already in progress.
  106864. */
  106865. get: function () {
  106866. return !!this._canvas && this._canvas.isRecording;
  106867. },
  106868. enumerable: true,
  106869. configurable: true
  106870. });
  106871. /**
  106872. * Stops the current recording before the default capture timeout passed in the startRecording
  106873. * functions.
  106874. */
  106875. VideoRecorder.prototype.stopRecording = function () {
  106876. if (!this._canvas || !this._mediaRecorder) {
  106877. return;
  106878. }
  106879. if (!this.isRecording) {
  106880. return;
  106881. }
  106882. this._canvas.isRecording = false;
  106883. this._mediaRecorder.stop();
  106884. };
  106885. /**
  106886. * Starts recording the canvas for a max duration specified in parameters.
  106887. * @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.
  106888. * @param maxDuration Defines the maximum recording time in seconds.
  106889. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  106890. * @return a promise callback at the end of the recording with the video data in Blob.
  106891. */
  106892. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  106893. var _this = this;
  106894. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  106895. if (maxDuration === void 0) { maxDuration = 7; }
  106896. if (!this._canvas || !this._mediaRecorder) {
  106897. throw "Recorder has already been disposed";
  106898. }
  106899. if (this.isRecording) {
  106900. throw "Recording already in progress";
  106901. }
  106902. if (maxDuration > 0) {
  106903. setTimeout(function () {
  106904. _this.stopRecording();
  106905. }, maxDuration * 1000);
  106906. }
  106907. this._fileName = fileName;
  106908. this._recordedChunks = [];
  106909. this._resolve = null;
  106910. this._reject = null;
  106911. this._canvas.isRecording = true;
  106912. this._mediaRecorder.start(this._options.recordChunckSize);
  106913. return new Promise(function (resolve, reject) {
  106914. _this._resolve = resolve;
  106915. _this._reject = reject;
  106916. });
  106917. };
  106918. /**
  106919. * Releases internal resources used during the recording.
  106920. */
  106921. VideoRecorder.prototype.dispose = function () {
  106922. this._canvas = null;
  106923. this._mediaRecorder = null;
  106924. this._recordedChunks = [];
  106925. this._fileName = null;
  106926. this._resolve = null;
  106927. this._reject = null;
  106928. };
  106929. VideoRecorder.prototype._handleDataAvailable = function (event) {
  106930. if (event.data.size > 0) {
  106931. this._recordedChunks.push(event.data);
  106932. }
  106933. };
  106934. VideoRecorder.prototype._handleError = function (event) {
  106935. this.stopRecording();
  106936. if (this._reject) {
  106937. this._reject(event.error);
  106938. }
  106939. else {
  106940. throw new event.error;
  106941. }
  106942. };
  106943. VideoRecorder.prototype._handleStop = function () {
  106944. this.stopRecording();
  106945. var superBuffer = new Blob(this._recordedChunks);
  106946. if (this._resolve) {
  106947. this._resolve(superBuffer);
  106948. }
  106949. window.URL.createObjectURL(superBuffer);
  106950. if (this._fileName) {
  106951. BABYLON.Tools.Download(superBuffer, this._fileName);
  106952. }
  106953. };
  106954. VideoRecorder._defaultOptions = {
  106955. mimeType: "video/webm",
  106956. fps: 25,
  106957. recordChunckSize: 3000
  106958. };
  106959. return VideoRecorder;
  106960. }());
  106961. BABYLON.VideoRecorder = VideoRecorder;
  106962. })(BABYLON || (BABYLON = {}));
  106963. //# sourceMappingURL=babylon.videoRecorder.js.map
  106964. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  106965. globalObject["BABYLON"] = BABYLON;
  106966. //backwards compatibility
  106967. if(typeof earcut !== 'undefined') {
  106968. globalObject["Earcut"] = {
  106969. earcut: earcut
  106970. };
  106971. }
  106972. return BABYLON;
  106973. });